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

Tomas Kormanak

09/07/2021, 12:42 PM
Hi, is it possible to cancel the scope without canceling parent scope? I need to cancel all jobs in scope, the scope itself but not parent scope. I am trying to avoid keeping reference to each job by myself and cancel all of them.
Copy code
coroutineScope {
    val job1 = launch { foo() }
    val job2 = launch { bar() }
    delay(1000)
    job1.cancel()
    job2.cancel()
}
I tried
Copy code
coroutineScope {
    launch { foo() }
    launch { bar() }
    delay(1000)
    cancel()
}
but it closes parent scope as well.
r

Richard Gomez

09/07/2021, 1:03 PM
It sounds like you want a SuperVisor scope.
t

Tomas Kormanak

09/07/2021, 1:06 PM
I don't think so. As I understand it
supervisorScope
does not propagate exceptions and does not close itself when child job fails. But when I cancel supervisorScope, it cancels parent scope as well. I might be missing something.
r

Richard Gomez

09/07/2021, 1:09 PM
Yeah, I was thinking that you'd wrap those jobs in a supervisor scope so they can be cancelled/fail without affecting it. However, I could be misremembering its utility. Perhaps a more apt solution is the cancelChildren function:
Cancels all children jobs of this coroutine using Job.cancel for all of them with an optional cancellation cause. Unlike Job.cancel on this job as a whole, the state of this job itself is not affected.
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/cancel-children.html
1
t

Tomas Kormanak

09/07/2021, 1:58 PM
this seems works:
Copy code
launch{
  coroutineScope {
    launch { foo() }
    launch { bar() }
    delay(1000)
    cancel()
  }
}
2 Views