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")
}
}
runBlockingis a normal function that creates new coroutine,coroutineScopeis a suspened function that creates new coroutine scope. FromrunBlockingdocs: 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