Coroutines: 运行 特定 CoroutineContext 上的 Deferred

Coroutines: run a Deferred on a specific CoroutineContext

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

Kotlin Coroutine Adapter 将 Retrofit 接口更改为 return a Deferred<T> 而不是 Call<T>.

我不明白的是如何在我想要的特定 CoroutineContext 中启动此 Deferred。考虑以下代码:


    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) returns 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() 调用不会启动另一个协程,它只是包装本机 Retrofit Call,以便其状态更改传播到 Deferred。 Retrofit 管理它自己的线程来执行它的操作,这就像没有协程包装器一样工作。如果您有特定的顾虑,您可以按照通常的方式通过配置 Retrofit 来管理它。

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