我正在尝试使用Kotlin协程结合Realm,使用withContext()在新线程中进行查询。
我观察到的是,在循环中线程会切换,导致Realm抛出以下异常:在错误的线程中访问Realm。Realm对象只能在创建它们的线程上访问。
作为 dispatchers.IO 文档在此提到:https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-i-o.html
该分发器与 [Default][Dispatchers.Default] 分发器共享线程,因此使用
我不明白为什么线程在循环中切换。 如何正确地使用协程管理 Realm 实例?
我观察到的是,在循环中线程会切换,导致Realm抛出以下异常:在错误的线程中访问Realm。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()
}
作为 dispatchers.IO 文档在此提到:https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-i-o.html
该分发器与 [Default][Dispatchers.Default] 分发器共享线程,因此使用
withContext(Dispatchers.IO) { ... }
不会导致实际切换到另一个线程;通常执行将继续在同一线程中进行。我不明白为什么线程在循环中切换。 如何正确地使用协程管理 Realm 实例?
images
是什么?它不是你在其他地方创建的 Realm 对象的集合,现在正在从另一个线程中访问吗? - Marko Topolnik