I have two completely independent `CorouteScopes`. Then I `launch` a coroutine in one of these scope...
n
I have two completely independent
CorouteScopes
. Then I
launch
a coroutine in one of these scopes. How to make this launched coroutine to be automatically cancelled if any of the two scopes is cancelled? Thanks.
j
The cancellation from the scope it is launched in is obviously already in place. For the second scope, you could register an
invokeOnCompletion
callback on its
Job
, and cancel your own coroutine from it manually if it's a cancellation.
πŸ™ 1
s
Copy code
scope2.launch(start = ATOMIC) {
  try {
    awaitCancellation()
  } finally {
    jobFromScope1.cancel()
  }
}
πŸ™ 1
βœ… 1
j
Sam's approach also should work. This is the one I meant:
Copy code
val jobFromScope1 = scope1.launch { ... }

scope2.job.invokeOnCompletion { cause ->
    if (cause != null) {
        jobFromScope1.cancel()
    }
}
πŸ‘ 1
πŸ™ 1
βœ… 1
a
πŸ‘€ 1
πŸ™ 1
k
While these both work, the more natural approach would be to have a third scope that's a parent of the two scopes you mention. Is that possible?
πŸ‘ 1
🚫 1
πŸ™ 1
s
Mine assumes
scope2
never terminates normally, only via cancellation/failure. That’s normally the case for custom scopes, but not for e.g. the
coroutineScope
function
πŸ‘πŸ» 1
n
Thanks for the lightning fast answers πŸ™‚