【发布时间】:2019-01-17 22:17:51
【问题描述】:
我正在尝试在 Android 应用中使用 Kotlin Coroutines,特别是我已经导入了 Kotlin Coroutine Adapter for Retrofit。
Kotlin Coroutine Adapter 更改 Retrofit 接口以返回 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) 返回Deferred<SomeModel>。
此代码有效,但我不确定 CoroutineContext 这个 foo.bar(param) 正在执行什么 (CommonPool??)。
如何明确指定我希望foo.bar(param) 在networkContext 中执行?
val response = async(networkContext) { foo.bar(param) }.await()
此代码不起作用,因为response 被评估为Deferred<SomeModel> 而不是SomeModel(我想要实现)。
【问题讨论】:
标签: android kotlin retrofit retrofit2 kotlin-coroutines