Search code examples
androidkotlinretrofit2kotlin-coroutines

Kotlin runBlocking always blocks main thread?


The official document about runBlokcing says

Runs a new coroutine and blocks the current thread until its completion. This function should not be used from a coroutine. It is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in main functions and in tests.

I think it means that runBlocking blocks only current thread.

but the Kotlin Coroutines Deep Dive by written Marcin Moskała.
In the book, it says

"Using a dispatcher, we can make runBlocking run on a different thread. But still, the thread on which this builder has been started will be blocked until the coroutines is done."

I understood it even if i change the current thread to worker(or other) thread with withContext or something and run the 'runBlocking' in the worker thread, the runBlocking will still block all the thread including main thread.

Therefore, what i want to know is runBlocking always block the main thread no matter what ways i use?


Solution

  • runBlocking only blocks a single thread, the one that it was called on.

    The book quote doesn’t contradict the documentation. Maybe your source of confusion about what the book is saying is thinking “the coroutine” in the phrase “until the coroutine is done” is referring to the outer coroutine that (shamefully) called runBlocking, when it is actually referring to the (unrelated) new coroutine that runBlocking builds.

    You should never use runBlocking inside a coroutine in the first place. There is no situation or condition where it would ever make sense to do that. Almost the only two places you will ever use runBlocking is directly in a JVM’s main() function or in a unit test. But also you might need it to use coroutines synchronously in a non-suspending callback function.