Sobes.tech
Junior — Middle

Can we talk about the hierarchy between coroutines during their execution?

sobes.tech AI

Answer from AI

Yes, in Kotlin, coroutines can have a hierarchical structure. When you launch a coroutine within the context of another coroutine (for example, using launch inside another coroutine), a parent-child relationship is established. If the parent coroutine is canceled, all its child coroutines are automatically canceled. This allows managing the lifecycle of groups of coroutines and preventing resource leaks.

Example:

val parentJob = CoroutineScope(Dispatchers.Default).launch {
    val childJob = launch {
        // work of the child coroutine
    }
}

// When parentJob is canceled, childJob will automatically be canceled
parentJob.cancel()