android - 我能够在android中从另一个线程而不是主线程更新ui
问题描述
我的方法中有以下代码
//main thread here in activity, oncreate method
updateUiFromDbButton.setOnClickListener() {
CoroutineScope(IO).launch {
val textToSet = getStringFromDb()
setText(textToSet)
}
}
and
private fun setText(text: String) {
val textView : TextView = findViewById(R.id.textView)
textView.text = text
}
getStringFromDb 看起来像这样
suspend private fun getStringFromDb(): String {
val allPersons = personDao.getAll()
var totalNames: String = ""
for (person in allPersons) {
totalNames += (person.firstName)
.plus(" ")
.plus(person.lastName)
.plus(System.lineSeparator())
}
return totalNames
}
让我真正感到困惑的是应用程序不会崩溃并且文本视图已更新——因为更新是在 io 线程中完成的。以下代码应该可以工作,我将代码放在 withContext(Main) 中
updateUiFromDbButton.setOnClickListener() {
CoroutineScope(IO).launch {
val textToSet = getStringFromDb()
withContext(Main) {
setText(textToSet)
}
setText(textToSet)
}
}
如果与Conte(Main)省略,我预计会崩溃。有人可以为我解释这个谜吗?
解决方案
Kotlin 协程实际上不是线程,它们是可以在一个线程中启动、在另一个线程中暂停和恢复的执行块。因此,您的代码有可能一直在同一个 UI 线程上运行。您可以检查的一件事是让您的 RoomDatabase 不接受来自 UI 线程的调用,并查看应用程序是否崩溃。
https://kotlinlang.org/docs/coroutines-basics.html#your-first-coroutine
推荐阅读
- android - SupportMapFragment 正在隐藏 admob 横幅
- android - Android - 即使设备处于打盹模式,音乐应用程序如何继续在网络上流式传输?
- javascript - 遇到两个孩子用同一个钥匙。密钥应该是唯一的,以便组件在更新时保持其身份
- python - Python:如何找到一个非常大的数的质因数?
- python - 如何在python Django项目中全局设置常量
- php - 使用 PHP 删除具有空子数组的多维数组
- android - 'if' 条件在 BaseAdapter 中无法正常工作
- javascript - AWS - 您提供的 AWS 访问密钥 ID 在我们的记录中不存在错误
- python-3.x - odoo 从代码向用户发送消息(通知)
- php - AJAX 数据捕获