【问题标题】:Proper use of coroutines Dispatcher Main and Default正确使用协程 Dispatcher Main 和 Default
【发布时间】: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


    【解决方案1】:

    由于herehere 所述的原因,您应该避免使用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()
    }
    

    文档

    【讨论】:

      猜你喜欢
      • 2020-03-21
      • 2019-03-25
      • 2019-06-07
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      相关资源
      最近更新 更多