我正在尝试将 realm 与 kotlin 协程一起使用,并使用 withContext() 在新线程中进行查询
我观察到的是线程在循环中切换,使领域抛出此异常:来自不正确线程的领域访问。Realm 对象只能在创建它们的线程上访问。
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()
}
作为调度员。此处提及的 IO 文档:https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-i-o.html
"此调度程序与 [默认][调度程序.默认] 调度程序共享线程,因此使用 * withContext(Dispatchers.IO) { ... }
不会导致实际切换到另一个线程; * 通常在同一线程中继续执行。
我不明白为什么线程在循环中切换。如何正确管理协程的领域实例?
您可以在协程中的另一个新单线程中运行 Realm。例如
val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
jobs.launch(dispatcher) {
// create new Realm instance
}
每次暂停协程时,在它恢复时,调度程序都会找到一个线程来运行它。它很可能与之前运行的线程不同。