I'm trying to use realm with kotlin coroutines and make queries inside a new thread using withContext()
What I observe is that threads are switching in the loop making realm throws this exception: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
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()
}
As the dispatchers.IO documentation mention here: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-i-o.html
"This dispatcher shares threads with a [Default][Dispatchers.Default] dispatcher, so using
* withContext(Dispatchers.IO) { ... }
does not lead to an actual switching to another thread;
* typically execution continues in the same thread."
I don't understand why thread are switching in the loop. How to manage realm instance with coroutine properly ?
You can run Realm in another new single thread in a Coroutine. For example
val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
jobs.launch(dispatcher) {
// create new Realm instance
}
Every time a coroutine is suspended, at the time it's resuming the dispatcher will find a thread for it to run on. It's quite likely that it will be a different thread than the one it ran on previously.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With