作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试在 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/
我是一名优秀的程序员,十分优秀!