I have two completely independent `CorouteScopes`....
# coroutines
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 ๐Ÿ™‚