【发布时间】:2019-10-14 16:14:00
【问题描述】:
我阅读了很多关于 Kotlin 协程的文档,但仍有一些疑问。我将 Retrofit 与协程一起使用,因此我需要使用 Dispatchers.IO 上下文进行请求,但使用 Dispatchers.Main 上下文中的结果将其分配给 ViewModel。我的代码是:
fun doHttpreq() {
viewModelScope.launch(Dispatchers.IO) {
try {
//should I call await() here? (I guess the correct way to keep execution of request outside of Main thread)
val request = RestClient.instance.getItems().await()
withContext(Dispatchers.Main) {
//or should I call await() here? (BUT need request to be executed outside of Main thread!)
if (request.isSuccessful) {
//asign items to ViewModel
} else {
//asign error to ViewModel
}
}
} catch (e: Exception) {
withContext(Dispatchers.Main) {
//asign error to ViewModel
}
}
}
}
【问题讨论】:
-
你只想要一个协程?
withContext很好.. 通过stackoverflow.com/questions/50230466/…