【发布时间】:2020-12-23 17:00:43
【问题描述】:
我正在尝试进行大量计算,然后想要更新 UI。
下面是我的代码:
private fun updateData() {
GlobalScope.launch(Dispatchers.Default){ //work on default thread
while (true){
response.forEach {
val out = doIntensiveWork()
withContext(Dispatchers.Main){ //update on main thread
_data.postValue(out)
delay(1500L)
}
}
}
}
}
这种使用协程的方式好吗?由于在 Main 上运行整个工作也没有可见的效果并且工作正常。
private fun updateData() {
GlobalScope.launch(Dispatchers.Main){ //work on Main thread
while (true){
response.forEach {
val out = doIntensiveWork()
_data.postValue(out)
delay(1500L)
}
}
}
}
推荐哪一个?
【问题讨论】:
标签: kotlin kotlin-coroutines coroutine