日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android使用suspendCancellableCoroutine将回调转换为协程

發布時間:2024/9/30 Android 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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将回调转换为协程的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。