0
votes

I am confused about runBlocking() and coroutineScope(). I have been reading a lot about this but I still get confused. I know that runBlocking() blocks the thread and coroutineScope() suspends the coroutine but I don't clearly understand what it means.

In this example, it prints A and then B. However, runBlocking() should block the thread until all it's code finishes. So A shouldn't be printed while the thread is blocked by runBlocking(). It should print B and then A.

runBlocking {
        launch {
            delay(1000L)
            println("A")
        }
        runBlocking {
            delay(3000L)
            println("B")
        }
    }

In this other code, it prints B and then A.

runBlocking {
        launch {
            delay(1000L)
            println("A")
        }
        runBlocking {
            Thread.sleep(3000L)
            println("B")
        }
    }

Thread.sleep() really blocks the thread and A cannot be printed while the thread is blocked.

What does it means to block the thread using runBlocking() if coroutines in this thread can be executed while the thread is blocked?

What's the difference between runBlocking() and coroutineScope() if this code has the same behaviour as the first one?

runBlocking {
        launch {
            delay(1000L)
            println("A")
        }
        coroutineScope {
            delay(3000L)
            println("B")
        }
    }
1
"What's the difference between runBlocking() and coroutineScope()?", runBlocking is a normal function that creates new coroutine, coroutineScope is a suspened function that creates new coroutine scope. From runBlocking docs: 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., just don't use it like that. - IR42

1 Answers

0
votes

The entire idea of using a runBlocking is when you need your code inside your runblocking thread to be executed at once, when you call runblocking : it means "block until whatever is inside this block is finished" when you call a parent runblocking it will just block until your code inside that is executed, but in case of coroutinescope you can always map that to a specific thread mode. I suggest you to clear your basics with coroutines first!