Reputation: 191
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
}
Upvotes: 10
Views: 11564
Reputation: 125
Dispatcher typically does not lead to an actual switching to another thread. In such scenarios, * the underlying implementation attempts to keep the execution on the same thread on a best-effort basis.
https://github.com/Kotlin/kotlinx.coroutines/pull/3236/files
Upvotes: -1
Reputation: 28026
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
Upvotes: 15