What's the use of runBlocking in kotlin if it blocks the current thread?

Viewed 570

I'm currently working on a codebase that is using runBlocking in a lot of places. Here is an example

fun doSomeComputation() {
    val rows = runBlocking { //suspend function which queries database }
    //rows is used for further computation
}

From what I understand runBlocking blocks the current thread. So what is the benefit we are exactly getting by using it instead of using regular function? Read somewhere we use async code so that thread is not blocked and UI doesn't become unresponsive but how is using runBlocking async code since it is blocking the thread?
I had the same doubt in javascript async/await Since thread gets blocked why even use await?

1 Answers

This is exactly why we should not use runBlocking() as you do. runBlocking() is useful for starting our application, for example we can put a single runBlocking() in the main() to bootstrap coroutines and then we don't use it anywhere else. It is also useful to bridge suspendable and non-suspendable code if blocking is our expected result. But otherwise, we should avoid using it.

If we need to bridge classic and suspendable code, but we don't want to block the thread, then we need to stick to classic asynchronous techniques like futures or callbacks.

Related