正确使用协程 Dispatcher Main 和 Default

Proper use of coroutines Dispatcher Main and Default

我正在尝试进行杯重计算,然后想更新 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)
                }
            }
        }
}

推荐哪一个?

出于 here and 所述的原因,您应该避免使用 GlobalScope

并且您应该考虑在 main thread

之外进行大量计算

suspen fun doHeavyStuff(): Result = withContext(Dispatchers.IO) { // or Dispatchers.Default
 // ...
}

suspend fun waitForHeavyStuf() = withContext(Dispatchers.Main) {
  val result = doHeavyStuff() // runs on IO thread, but results comes back on Main thread
  updateYourUI()
}

文档