If I cancel an entire coroutineScope, will launche...
# coroutines
c
If I cancel an entire coroutineScope, will launches still be accepted with the same scope? I'm trying to resolve a debate.
o
no, they will all be cancelled
c
So all future work will be cancelled?
o
correct
if you want to have this functionality, you can create a scope with a
SupervisorJob()
and cancel all the children of the job instead
c
I think I do want the actual behavior. I just wasn't sure about it.
Thank you!
o
you can check yourself with:
Copy code
suspend 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
Copy code
Yes, this runs!
Finished.
and the alternative:
Copy code
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
Copy code
Yes, this runs!
Yes, this runs too!
Finished.
ah, in fact you don't even need
SupervisorJob()
here -- cancellation of parent only occurs with an exception, not when cancelling normally via
cancel()