supervisorScope cancels its parent

Viewed 560

I was playing around with the supervisorScope in android. The documentation says the following.

A failure of a child does not cause this scope to fail and does not affect its other children, so a custom policy for handling failures of its children can be implemented. See SupervisorJob for details. A failure of the scope itself (exception thrown in the block or cancellation) fails the scope with all its children, but does not cancel parent job.

But consider the following code

viewModelScope.launch {

       launch { someLongJob() }

       supervisorScope {
            launch { jobTwo() }
            launch { jobThree() }
            delay(500)
            throw ArithmeticException()
       }

}

private suspend fun someLongJob() {
    try {
        delay(Long.MAX_VALUE)
    } catch (e: Exception) {
        Log.d(TAG, "Long job cancelled")
    }
}

private suspend fun jobOne() {
    delay(1000)
    throw ArithmeticException()
}

private suspend fun jobTwo() {
    try {
        delay(2000)
    } catch (e: Exception) {
        Log.d(TAG, "Job 2 cancelled")
        throw e
    }
    Log.d(TAG, "Job 2 completed successfully")
}

private suspend fun jobThree() {
    try {
        delay(3000)
    } catch (e: Exception) {
        Log.d(TAG, "Job 3 cancelled")
        throw e
    }
    Log.d(TAG, "Job 3 completed successfully")
}

It produces the following output

D/TEST: Job 2 cancelled

D/TEST: Job 3 cancelled

D/TEST: Long job cancelled

---beginning of crash

My doubt is, as per documentation mentioned in bold, the supervisorScope should not cancel its parent even when the scope itself fails meaning that long job(which is running in the parent job) should not be cancelled. But the output clearly shows that the Long job which runs in the parent also gets cancelled. Why?

1 Answers

supervisorScope is a function call just like any other. In your case, it completed abruptly, with an exception. Since you didn't catch it, the same exception caused the launch block to complete abruptly, and that caused it to be cancelled. Then, following the fundamental principles of structured concurrency, cancellation spread inward and cancelled all the child jobs.

Related