gpt4 book ai didi

android - 协程 : run a Deferred on a specific CoroutineContext

转载 作者:行者123 更新时间:2023-11-29 23:41:41 24 4
gpt4 key购买 nike

我正在尝试在 Android 应用程序中使用 Kotlin 协程,特别是我已经导入了 Kotlin Coroutine Adapter for Retrofit .

Kotlin Coroutine Adapter 更改 Retrofit 接口(interface)以返回 Deferred<T>而不是 Call<T> .

我不明白的是如何启动这个Deferred特别是CoroutineContext我想要的。考虑以下代码:


class MyViewModel @Inject constructor(
private val foo: Foo,
@Named("ui") private val uiContext: CoroutineContext,
@Named("network") private val networkContext: CoroutineContext
) : ViewModel() {

fun performSomeJob(param: String) {
launch(uiContext) {
try {
val response = foo.bar(param).await()
myTextView.setText(response.name)
} catch (error: Throwable) {
Log.e(error)
}
}
}

在哪里foo.bar(param)返回 Deferred<SomeModel> .

此代码有效,但我不确定是什么 CoroutineContext这个foo.bar(param)正在执行(CommonPool ??)。

如何明确指定,我想要 foo.bar(param)networkContext 中执行?


val response = async(networkContext) { foo.bar(param) }.await()

此代码无效,因为 response被评估为 Deferred<SomeModel>而不是 SomeModel (这是我想要实现的)。

最佳答案

foo.bar() 调用不会启动另一个协程,它只是包装 native Retrofit Call 以便其状态更改传播到 Deferred 。 Retrofit 管理它自己的线程来执行它的操作,这就像没有协程包装器一样工作。如果您有特定的顾虑,可以通过以常规方式配置 Retrofit 来管理它。

唯一对您重要的是您的协程在 UI 上下文中执行。

关于android - 协程 : run a Deferred on a specific CoroutineContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51784130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com