kotlin-coroutines - 在协程中完成后台工作后更新 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 的正确方法吗?
解决方案
实际上,事情要容易得多。您不应该管理自己的协程范围,看看LifecycleScope,它已经绑定到活动生命周期。但更好的方法是将ViewModelScope与ViewModel库结合使用。
请注意,默认情况下两者都viewModelScope
使用lifecycleScope
,Dispatchers.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
}
}
推荐阅读
- python - Beatifulsoup 没有返回页面的完整 html
- python - pyshark:访问原始 udp 有效负载
- mysql - 使用一个命令同步删除多个表中的数据
- android - TextInputLayout - setError 不会将浮动提示颜色更改为错误颜色
- php - JMS 组序列化和 PagerFantaBundle
- python - 如何在python中将十进制数字字符串转换为日期时间格式?
- odoo-8 - “mail_message”表中的 Odoo 8“message_id”列
- ios - UIStackView,通过调整动画大小隐藏子视图
- django - 在通用更新视图中使用内联表单集通过外键编辑相关对象
- square-connect - 使用 Connect V2 时库存管理不起作用