android - 将领域与协程一起使用时从不正确的线程访问领域
问题描述
我正在尝试将领域与 kotlin 协程一起使用,并使用 withContext() 在新线程中进行查询
我观察到的是线程在循环中切换,使得领域抛出这个异常:从不正确的线程访问领域。领域对象只能在创建它们的线程上访问。
withContext(Dispatchers.IO) {
val realm = Realm.getDefaultInstance()
val images = mutableListOf<String>("id1", "id2", ...)
for (imageId in images) {
println("THREAD : ${Thread.currentThread().name}")
val image = realm.where<Image>().equalTo("imageId", imageId).findFirst()
delay(1000) // Can lead to an actual switching to another thread
}
realm.close()
}
正如 dispatchers.IO 文档在这里提到的那样:https ://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-io.html
“此调度程序与 [Default][Dispatchers.Default] 调度程序共享线程,因此使用 *withContext(Dispatchers.IO) { ... }
不会导致实际切换到另一个线程;* 通常在同一个线程中继续执行。”
我不明白为什么线程在循环中切换。如何使用协程正确管理领域实例?
解决方案
您可以在协程中的另一个新单线程中运行 Realm。例如
val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
jobs.launch(dispatcher) {
// create new Realm instance
}
推荐阅读
- django - 如何在将文件保存到 django rest_framework 中的数据库之前重命名文件
- r - 使用存储在列表中的数据帧内的 table() 创建新的数据帧
- javascript - 用 Javascript 编译 Latex
- html - 淘汰赛 JS 复选框列表不绑定
- php - 逐张从excel文件中提取数据。单工lsx
- c - Different ways of suppressing 'uninitialized variable warnings' in C
- c++ - Why is a member in a primary class template not declared in the scope of the specialized class?
- docker - Docker compose:需要一个映射或映射列表以进行合并,但找到了标量
- javascript - 防止android webview中的无效输入值更改
- javascript - 如何使用 javascript 获取附加的部分 url