首页 > 解决方案 > 在主线程上访问 ROOM DB

问题描述

我在我的应用程序中使用 ROOM DB,我的代码如下所示 -

这是我的回购代码 -

override suspend fun storeDataToCache(dataModel: DataModel) {
    //Printing out thread name gives me main thread still
    personalDataDao.insertData(dataModel)
}

这是我的 DAO 代码 -

@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertData(dataModel: DataModel)

这行得通。

但是,当我删除suspend关键字时,它给了我-

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

这很好,因为我试图在主线程上访问 ROOM DB。

但我的问题是,使用suspend关键字并且不进行线程切换,例如。withContext(Dispatchers.Default), 它是如何工作的?ROOM DB 是否在内部对工作线程执行所有操作?

标签: androidandroid-roomkotlin-coroutines

解决方案


是的,当您将该函数标记为挂起时,Room 会在后台/工作线程中执行查询,然后在完成后恢复调用协程并返回结果(或异常)。这意味着您不需要做类似的事情withContext(Dispatchers.IO) { },您可以直接调用该函数。


推荐阅读