Please help understand coroutine launch

Hello, could you help me understand what’s the different between the below codes. Thanks. What’s the fundamental different between using scope.launch and launch inside a launch?

fun main() {
val scope = CoroutineScope(CoroutineName(“myscope”) + Dispatchers.IO)
runBlocking{
val job = scope.launch {
scope.launch { // <----
delay(1000L)
println(“task1”)
}
scope.launch {
delay(900L)
println(“task2”)
}
}
job.join()
}
}

VS

fun main() {
val scope = CoroutineScope(CoroutineName(“myscope”) + Dispatchers.IO)
runBlocking{
val job = scope.launch {
launch { // <----
delay(1000L)
println(“task1”)
}
launch {
delay(900L)
println(“task2”)
}
}
job.join()
}
}

The first one will not print anything but the second one prints
"
task2
task1
"

If we do simply launch {}, that usually means the new coroutine is a child of the current coroutine. scope.launch {} means the new coroutine is a child of the scope.

In the second example, job.join() waits for the job, including its children, so both launched coroutines. In the first example, job.join() doesn’t wait for these coroutines.

1 Like

Thanks