https://kotlinlang.org logo
#coroutines
Title
# coroutines
k

kevinskrei

04/04/2019, 7:08 PM
I'm attempting to use Realm in a suspend function. Realm only allows access to objects on the same thread. Is there a way to ensure that when a suspending call is made inside that function that it returns to the same thread as the caller? I've read about ThreadLocal but i've only seen examples when launching a coroutine and not within a suspend function. Or, is the only way to control the thread switching is from the parent calling
<http://GlobalScope.xxx|GlobalScope.xxx>
? For example
Copy code
suspend fun sync() {
   Realm.getDefaultInstance().use { realm ->
          val variable = realm.getSomeVar()
          val result = service.execute() //<- suspending function
          val x = variable.y //<- Error because it returns to a different thread
   }
}
Thank you
w

withoutclass

04/04/2019, 7:10 PM
You could probably use a fixed size thread pool of 1 to do all your Realm interactions
something like
val realmDispatcher = Executors.newFixedThreadPool(1).asCoroutineDispatcher()
❤️ 1
10 Views