首页 > 解决方案 > 我能够在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)省略,我预计会崩溃。有人可以为我解释这个谜吗?

标签: androidkotlinkotlin-coroutineskotlin-android-extensions

解决方案


Kotlin 协程实际上不是线程,它们是可以在一个线程中启动、在另一个线程中暂停和恢复的执行块。因此,您的代码有可能一直在同一个 UI 线程上运行。您可以检查的一件事是让您的 RoomDatabase 不接受来自 UI 线程的调用,并查看应用程序是否崩溃。

https://kotlinlang.org/docs/coroutines-basics.html#your-first-coroutine


推荐阅读