Android使用suspendCancellableCoroutine将回调转换为协程
生活随笔
收集整理的這篇文章主要介紹了
Android使用suspendCancellableCoroutine将回调转换为协程
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
轉(zhuǎn)載請(qǐng)標(biāo)明出處:http://blog.csdn.net/zhaoyanjun6/article/details/122058124
本文出自【趙彥軍的博客】
文章目錄
- suspendCancellableCoroutine
- suspendCancellableCoroutine 和 suspendCoroutine 區(qū)別
suspendCancellableCoroutine
普通的回調(diào)函數(shù):
interface Result<T> {fun onSuccess(t: T)fun onFailed(e: Exception) }回調(diào)方法,模擬耗時(shí)操作
fun longTimeMethod(result: Result<String>) {thread {Thread.sleep(5000)if (System.currentTimeMillis() % 10 > 6) {result.onSuccess("${System.currentTimeMillis()}")} else {result.onFailed(Exception("FAILED"))}}}去掉回調(diào),轉(zhuǎn)換為掛起函數(shù):
suspend fun getResult(): String =suspendCancellableCoroutine {longTimeMethod(object : Result<String> {override fun onSuccess(t: String) {if (it.isCancelled) returnit.resume(t)}override fun onFailed(e: Exception) {it.resumeWithException(e)}})}使用:
GlobalScope.launch {try {val result = getResult()} catch (exception: Exception) {}}源碼分析:
我們看一下 it.resume() 、it.resumeWithException()方法,其實(shí)是調(diào)用 resumeWith(result: Result)
suspendCancellableCoroutine 和 suspendCoroutine 區(qū)別
- 使用 suspendCancellableCoroutine 和 suspendCoroutine 都可以將回調(diào)函數(shù)轉(zhuǎn)換為協(xié)程
- SuspendCancellableCoroutine 返回一個(gè) CancellableContinuation, 它可以用 resume、resumeWithException 來處理回調(diào) 和拋出 CancellationException 異常。它與 suspendCoroutine的唯一區(qū)別就是 SuspendCancellableCoroutine 可以通過 cancel() 方法手動(dòng)取消協(xié)程的執(zhí)行,而 suspendCoroutine 沒有該方法。
- 盡可能使用 suspendCancellableCoroutine 而不是 suspendCoroutine ,因?yàn)閰f(xié)程的取消是可控的
舉個(gè)例子:使用網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù)時(shí),如果請(qǐng)求時(shí)間過長,用戶可以手動(dòng)取消掉協(xié)程的執(zhí)行。這時(shí)會(huì)拋出一個(gè) CancellationException 異常,但是將該異常try{}catch{}捕獲后就不會(huì)影響后續(xù)代碼的執(zhí)行。而使用 suspendCoroutine 只能干等著被 resume 或者 resumeWithException ,因?yàn)樗鼪]有該功能。
總結(jié)
以上是生活随笔為你收集整理的Android使用suspendCancellableCoroutine将回调转换为协程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android 图片加载框架Coil使用
- 下一篇: Android通过Scheme协议打开A