CoroutineDispatcher on a Looper Thread

Viewed 1078

I have a helper class for doing some jobs on database Realm. As you know, we have some restriction in working with realm, such as:

  1. Realm instance is not auto refresh on non looping thread.
  2. Realm objects can only be accessed on the thread they were created

My Helper class extends CoroutineScope and to provide a CoroutineContext I used this code Executors.newSingleThreadExecutor().asCoroutineDispatcher()

But my problem is all jobs on this CoroutineScope is running on non looping thread so How can I create a ExecutorCoroutineDispatcher which is run on a single looper thread.

It's obvious I don't want to use Dispatchers.Main because it supposes to do jobs on my Database

1 Answers

Although the OP's problem has already solved by @Pawel's comment, for someone who may need a certain code snippet:

// prepare a HandlerThread and start it
val handlerThread = HandlerThread("MyThread")
handlerThread.start()
// obtain Handler from the HandlerThread's looper
val handler = Handler(handlerThread.looper)
// Now you can get CoroutineDispatcher from the Handler
val myDispatcher = handler.asCoroutineDispatcher()

Or shortly using Scope functions:

val myDispatcher = HandlerThread("MyThread")
    .apply { start() }
    .looper.let { Handler(it) }
    .asCoroutineDispatcher()
Related