首页 > 解决方案 > 在协程中完成后台工作后更新 UI

问题描述

我遇到了以下代码示例,它展示了如何使用协程在 IO 线程上运行后台代码,然后在需要更新 UI 时切换到 UI(主)线程:

class YourActivity : CoroutineScope {
    private lateinit var job: Job

    // context for io thread
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.IO + job

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    job = Job()
  }

    fun toDoSmth() {
        launch {
            // task, do smth in io thread
            withContext(Dispatchers.Main) {
              // do smth in main thread after task is finished
            }                  
        }
    }

   override fun onDestroy() {
      job.cancel()
      super.onDestroy()
   }
}

这是后台工作完成后更新 UI 的正确方法吗?

标签: kotlin-coroutines

解决方案


实际上,事情要容易得多。您不应该管理自己的协程范围,看看LifecycleScope,它已经绑定到活动生命周期。但更好的方法是将ViewModelScopeViewModel库结合使用。

请注意,默认情况下两者都viewModelScope使用lifecycleScopeDispatchers.Main因此您应该将 IO 调度程序传递给该launch方法,例如:

viewModelScope.launch(Dispatchers.IO) {
    // task, do smth in io thread
    withContext(Dispatchers.Main) {
      // do smth in main thread after task is finished
    }
}

推荐阅读