colintheshots
06/09/2020, 8:48 PMoctylFractal
06/09/2020, 8:48 PMcolintheshots
06/09/2020, 8:49 PMoctylFractal
06/09/2020, 8:49 PMSupervisorJob()
and cancel all the children of the job insteadcolintheshots
06/09/2020, 8:49 PMoctylFractal
06/09/2020, 8:52 PMsuspend fun main() {
val scope = CoroutineScope(Job())
scope.launch {
println("Yes, this runs!")
}.join()
scope.cancel()
scope.launch {
println("No, this won't run!")
}.join()
println("Finished.")
}
gives
Yes, this runs!
Finished.
suspend fun main() {
val scope = CoroutineScope(SupervisorJob())
scope.launch {
println("Yes, this runs!")
}.join()
scope.coroutineContext[Job]!!.children.forEach { it.cancel() }
scope.launch {
println("Yes, this runs too!")
}.join()
println("Finished.")
}
gives
Yes, this runs!
Yes, this runs too!
Finished.
SupervisorJob()
here -- cancellation of parent only occurs with an exception, not when cancelling normally via cancel()