Sobes.tech
Junior — Middle

How does coroutineScope detect that its coroutines have been canceled?

sobes.tech AI

Answer from AI

coroutineScope in Kotlin coroutines detects the cancellation of its child coroutines through the coroutine context cancellation mechanism. If one of the coroutines inside coroutineScope is canceled (for example, due to an exception or explicit cancellation), then the entire coroutineScope receives a cancellation signal.

This happens because all coroutines inside coroutineScope inherit a common CoroutineContext, which contains a Job. When this Job is canceled, all child coroutines are also canceled.

Thus, coroutineScope monitors the state of its child coroutines through the shared context and reacts to their cancellation by stopping execution and throwing a CancellationException, if necessary.

Example:

suspend fun example() = coroutineScope {
    val job = launch {
        // some work
        delay(1000)
    }
    delay(500)
    job.cancel() // cancel the child coroutine
    // coroutineScope will detect the cancellation and will be interrupted
}