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