gpt4 book ai didi

android - Kotlin 协程不等待完成

转载 作者:太空狗 更新时间:2023-10-29 14:42:24 28 4
gpt4 key购买 nike

我有一个遗留项目,我想在联系后端时使用协程。后端由 Hybris 提供的 sdk 处理。例如,它使用 volley,并带有一些回调。我想要的是用协程包装这些回调。但我遇到的问题是协程没有等待完成,它启动了协程,并继续转到下一行,方法返回一个值,并且在协程完成很久之后。我的代码:

suspend  fun ServiceHelper.getList(): ListOfWishes {

return suspendCancellableCoroutine { continuation ->

getAllLists(object : ResponseReceiver<ListOfWishes> {
override fun onResponse(response: Response<ListOfWishes>?) {
continuation.resume(response?.data!!)

}

override fun onError(response: Response<ErrorList>?) {
val throwable = Throwable(Util.getFirstErrorSafe(response?.data))
continuation.resumeWithException(throwable)
}
}, RequestUtils.generateUniqueRequestId(), false, null, object : OnRequestListener {
override fun beforeRequest() {}
override fun afterRequestBeforeResponse() {}
override fun afterRequest(isDataSynced: Boolean) {}
})
}
}

辅助方法:

suspend fun ServiceHelper.wishLists(): Deferred<ListOfWishes> {
return async(CommonPool) {
getWishList()
}
}

协程调用的地方:

    fun getUpdatedLists(): ListOfWishes? {
val context = Injector.getContext()
val serviceHelper = Util.getContentServiceHelper(context)
var list = ListOfWishLists()
launch(Android) {
try {
list = serviceHelper.wishLists().await()
} catch (ex: Exception){
Timber.d("Error: $ex")
}
}
return list

因此,它不会等待 serviceHelper.wishLists().await() 完成,而是返回列表。我还尝试让该方法返回一个 runBlocking{},但这只会阻塞 UI 线程而不会结束协程。

最佳答案

协程不是这样工作的。 getUpdatedLists() 方法不能等待协程完成其执行而不是 suspend 方法本身。如果 ActivityFragment 中定义了方法 getUpdatedLists(),您可以启动协程并执行某些操作,例如在 serviceHelper.wishLists().await() 执行后更新 UI。它看起来像这样:

fun loadUpdatedLists() {
val context = Injector.getContext()
val serviceHelper = Util.getContentServiceHelper(context)
lifecycleScope.launch {
try {
val list = serviceHelper.wishLists().await()
// use list object, for example Update UI
} catch (ex: Exception){
Timber.d("Error: $ex")
}
}
}

lifecycleScope - CoroutineScope 绑定(bind)到 LifecycleOwnerLifecycle。要使用它,请添加依赖项:

androidx.lifecycle:lifecycle-runtime-ktx:2.4.0 or higher.

关于android - Kotlin 协程不等待完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45833042/

28 4 0
文章推荐: javascript - Android 的 Cordova 插件中是否有可用的 onDestroy Hook ?
文章推荐: javascript - 将点击事件添加到 Jquery UI Accordion 页眉
文章推荐: javascript - jquery 在
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com