Trying to understand why two code snippets work th...
# coroutines
s
Trying to understand why two code snippets work the way they do regarding SupervisorJob and cancellation of children. More in thread
We got simple functions one, two three:
Copy code
suspend fun one() {
    println("one start")
    throw Exception("")
    println("one end")
}

fun two() {
    println("two start")
    throw Exception("")
    println("two end")
}

fun three() {
    println("three start")
    println("three end")
}
One main function is this
Copy code
suspend fun main() {
    val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
	val job = scope.launch {
        launch { one() }
        launch { two() }
    	launch { three() }
        println("done")
    }
	job.join()
}
and the second one is this (Adding an extra supervisorScope in there)
Copy code
suspend fun main() {
    val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
	val job = scope.launch {
        supervisorScope {
	        launch { one() }
	        launch { two() }
        	launch { three() }
            println("done")
        }
    }
	job.join()
}
The first one, sometimes runs and prints
Copy code
done
one start
and sometimes
Copy code
one start
done
three start
three end
two start
The second one consistently prints out all of them as expected. one start, two start, done and the entire three prints.
Copy code
one start
done
three start
three end
two start
As far as I understand,
scope
having a
SupervisorJob()
should make it so that child jobs should not cancel the parent and therefore the other children too. So I do not understand how the other launches may never be going off. Am I missing something here? #1 and #2 can be run here in play.kotlinlang
s
The
SupervisorJob
only changes its relationship with its own direct children. The second job you create, via scope.launch, isn't a supervisor job, so it still cancels its children on failure.
s
Right! I'm one layer deep there since I'm already inside the
launch
. Yeah you're right it does make sense then.