Dan Lukashevich
01/06/2023, 11:57 AMdelay
in the very first example:
fun main() = runBlocking { // this: CoroutineScope
launch { // launch a new coroutine and continue
delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
println("World!") // print after delay
}
println("Hello") // main coroutine continues while a previous one is delayed
}
The code block above prints:
Hello
World!
However the code block below prints the same 🙃
fun main() = runBlocking {
launch {
println("World!")
}
println("Hello")
}
However the output changes if we’re using Dispatcher.Unconfined
in the launch
coroutine builder.
Do you have an idea how to update it without changing the default dispatcher and the same time using runBlocking
so that delay
is noticeable and the result could be different?
Hello
World!
If there is a delay
World!
Hello
If there is no delayJoffrey
01/06/2023, 12:00 PMlaunch
runs concurrently with the rest of the code. Conceptually, the delay is useful because you don't need the reader to understand the fact that runBlocking
creates a single-threaded event loop that guarantees that the body of launch
will run after the rest no matter whether it suspends or not.Joffrey
01/06/2023, 12:02 PMrunBlocking
with its default single-threaded event loop disptacher AND have non-deterministic / time-sensitive behaviour with delays. You would have to make it multi-threaded. For instance by passing Dispatchers.Default
to runBlocking
Joffrey
01/06/2023, 12:03 PMlaunch
blocks, and add a delay in front of each print.Dan Lukashevich
01/06/2023, 1:07 PMrunBlocking
. Well I think it’s much more clear in terms of delays:
fun main() = runBlocking {
launch {
delay(2000L)
println("World!")
}
delay(1000L)
println("Hello")
}
It is also clear that runBlocking
is a coroutine itself.