android - 在主线程上访问 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 是否在内部对工作线程执行所有操作?
解决方案
是的,当您将该函数标记为挂起时,Room 会在后台/工作线程中执行查询,然后在完成后恢复调用协程并返回结果(或异常)。这意味着您不需要做类似的事情withContext(Dispatchers.IO) { }
,您可以直接调用该函数。
推荐阅读
- reactjs - ReactJS如何仅在条件为真时获取?
- android - 在 Android Studio 中,ListView 中的按钮不起作用
- rust - 为什么我收到错误:捕获的变量无法逃脱 `FnMut` 闭包体?
- discord - 我怎样才能使不和谐的机器人耳聋?
- r - 索引匹配双列,如 Excel,但在 R 中
- php - 如何使用 post 方法传递变量?
- mongodb - 当我尝试运行 mongo 命令时,我得到以下错误
- javascript - javascript 错误:无法读取未定义的属性“scrollIntoView”
- javascript - 通过休息 POST 表单数据
- c - 从数组中获取单个元素?