Junior — Middle
Kas emaltüüp korutina võib lõpetada enne selle sees käivitunud lapsekorutina lõppemist?
sobes.tech AI
Vastus AI-lt
In Kotlin, a parent coroutine can finish earlier than a child coroutine if the child coroutine is started in another context or in the global scope.
However, if the child coroutine is started in the parent's context (for example, via launch in the parent's CoroutineScope), then the parent coroutine will wait for the child coroutines to complete and will finish later or simultaneously with them.
Example:
runBlocking {
val job = launch {
launch {
delay(1000)
println("Child coroutine finished")
}
println("Parent coroutine finished")
}
job.join()
}
In this example, the parent coroutine will not finish until the child coroutines are completed.
If, on the other hand, the child coroutine is started in GlobalScope, then the parent coroutine may finish earlier.