Hi there :wave: :slightly_smiling_face: I’m playin...
# coroutines
d
Hi there 👋 🙂 I’m playing around with the coroutines basics doc and I noticed the useless of the
delay
in the very first example:
Copy code
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:
Copy code
Hello
World!
However the code block below prints the same 🙃
Copy code
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?
Copy code
Hello
World!
If there is a delay
Copy code
World!
Hello
If there is no delay
j
The point of this doc is to make people familiar with concurrency concepts: understanding that
launch
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.
You cannot use
runBlocking
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
One way to make it delay-sensitive could be to launch both print statements inside
launch
blocks, and add a delay in front of each print.
d
Come up with a single launch block just adding another delay to the
runBlocking
. Well I think it’s much more clear in terms of delays:
Copy code
fun main() = runBlocking {
    launch {
        delay(2000L)
        println("World!")
    }
    delay(1000L)
    println("Hello")
}
It is also clear that
runBlocking
is a coroutine itself.