Does runBlocking(Dispatchers.IO) block the main thread even the the coroutine context is not Dispatchers.Main?

Viewed 3895

I'm learning Android with Kotlin and I have learned that the recommended way to start coroutines without blocking the main thread is to do something like below

MainScope().launch {
  withContext(Dispatchers.IO) {
    // Do IO work here
  }
}

But I was also wondering if the call below not would block the main thread because it's still using Dispatchers.IO

runBlocking(Dispatchers.IO) {
  // Do IO work here
}
2 Answers

If you call runBlocking(Dispatchers.IO) from the main-thread, then the main-thread will be blocked while the coroutine finishes on the IO-dispatcher.

This is what the documentation says about this:

When CoroutineDispatcher is explicitly specified in the context, then the new coroutine runs in the context of the specified dispatcher while the current thread is blocked. If the specified dispatcher is an event loop of another runBlocking, then this invocation uses the outer event loop.

You can find the documentation here: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html

Related