I'm learning Kotlin coroutines and I was trying to understand the coroutine scope. As per the Kotlin guide on structured concurrency,
An outer scope cannot complete until all its children coroutines complete.
I created an example as below:
fun exampleCoroutine() {
println("Corutine started")
runBlocking {
launch {
delay(2000)
launch { //child launch
println("nested child")
}
println("parent")
}
launch {
delay(1000)
println("in the second coroutine")
}
println("Hello")
}
}
And I get the below output
Corutine started
Hello
in the second coroutine
parent
nested child
As per my understanding on how coroutine scopes work, I assumed that "nested child" would print before "parent". As that's clearly not the case, I want to know why "nested child" is printing after "parent".
And if my understanding is wrong, please feel free to correct me.
From the documentation of
launch:In other words, it launches a coroutine and returns immediately. The launched coroutine executes asynchronously. Note also that
launchis not asuspendfunction.You quoted:
Looking at the following segment of your code:
That quote is saying the coroutine created by the "parent"
launchcannot complete until the child coroutine created by the "child"launchcompletes. The last print statement in the block is not when the coroutine completes. A coroutine completes when the block returns and, as mentioned in the quote, all children coroutines have also completed.You can see this better if you make use of
invokeOnCompletionfrom theJobobjects returned bylaunch. For example, the following:Kotlin Playground: https://pl.kotl.in/Oar099RZs
Outputs:
Note that although the last statement of "Parent-1" is executed before "Child-1" completes, "Parent-1" does not complete until after "Child-1" completes.