https://kotlinlang.org logo
#coroutines
Title
# coroutines
c

colintheshots

06/09/2020, 8:48 PM
If I cancel an entire coroutineScope, will launches still be accepted with the same scope? I'm trying to resolve a debate.
o

octylFractal

06/09/2020, 8:48 PM
no, they will all be cancelled
c

colintheshots

06/09/2020, 8:49 PM
So all future work will be cancelled?
o

octylFractal

06/09/2020, 8:49 PM
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

colintheshots

06/09/2020, 8:49 PM
I think I do want the actual behavior. I just wasn't sure about it.
Thank you!
o

octylFractal

06/09/2020, 8:52 PM
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()
4 Views