Android - 用于处理 IllegalStateException : Cannot access database on the main thread 的 Kotlin 协程

标签 android android-room kotlin-coroutines illegalstateexception

在我的 Android 应用程序中,我使用 Room 作为本地数据库来存储用户的帐户信息。当我发出一个简单的 Room 请求来检索存储在数据库中的 Account 对象时,我收到以下错误消息:

java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

这是我发出本地数据库请求的 fragment 代码:

// AccountInformationFragment.kt


accountDataFragmentViewModel.retrieveAccountData(accountId).observe(viewLifecycleOwner, Observer {
       // do some stuff
    })

ViewModel 类中,我实现了 retrieveAccountData(),如下所示:

    // AccountInformationFragmentViewModel.kt        

    // used to get the account from the local datasource
    fun retrieveAccountData(id:Long): LiveData<Account>{
        val result = MutableLiveData<Account>()
        viewModelScope.launch {
            val account = authRepository.retrieveAccountData(id)
            result.postValue(account) 
        }
        return result
    }

Repository 类中,我实现了 retrieveAccountData(),如下所示:

// AccountRepository.kt

suspend fun retrieveAccountData(accId:Long): Account =
        accountDao.retrieveAccountData(accId)

我知道我必须使用某种 asnyc 操作,因为本地数据库操作在主线程上执行时可能需要很长时间。 但是在 ViewModel 类中,我在 viewModelScope 中启动了协程。这还不够吗?基于异常,似乎不是。那么,是否有人可以告诉我如何正确执行此操作。

编辑:

这是 Dao 类:

@Query("SELECT * FROM account_table WHERE id = :id")
fun retrieveAccountData(id: Long) : Account

提前致谢

最佳答案

根据 Room documentation ,如果您希望 Room 自动移动到后台线程来运行您的 @Query,您可以将您的方法设为 suspend 方法:

@Query("SELECT * FROM account_table WHERE id = :id")
suspend fun retrieveAccountData(id: Long) : Account

关于Android - 用于处理 IllegalStateException : Cannot access database on the main thread 的 Kotlin 协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64755925/

相关文章:

android - 从 ImageView 的 url 加载 svg 文件

android - 如何在 Jetpack Compose 上更改文本内容描述

android - 带有 completeSmart() 函数的 IntelliJ 实时模板错误

android - 组合两个具有相同观察者类型的 LiveData 对象

android - Coroutine GlobalScope 延迟触发

Android ViewModel 和 startActivity

android - 房间数据库抛出CursorWindowAllocationException

android - 即使重新安装后,ROOM 数据库中的数据也不会被删除

asynchronous - Kotlin 延续未恢复

android - 让暂停功能不返回任何东西