首页 > 解决方案 > 将领域与协程一起使用时从不正确的线程访问领域

问题描述

我正在尝试将领域与 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) { ... }不会导致实际切换到另一个线程;* 通常在同一个线程中继续执行。”

我不明白为什么线程在循环中切换。如何使用协程正确管理领域实例?

标签: androidkotlinrealmkotlinx.coroutines

解决方案


您可以在协程中的另一个新单线程中运行 Realm。例如

val dispatcher =  Executors.newSingleThreadExecutor().asCoroutineDispatcher()
jobs.launch(dispatcher) {
  // create new Realm instance
}

推荐阅读