I have a use-case where I need to cancel a corouti...
# coroutines
d
I have a use-case where I need to cancel a coroutine if either of two scopes cancel. That is it is possible for scope
A
to outlive scope
B
and vice versa, so if either of them stop I need to stop all of their coroutines. Is this possible using the
CoroutineScope()
factory function?
k
I may be misunderstanding your question but it seems like nesting coroutine scopes would do the trick.
Copy code
suspend fun foo() = coroutineScope {
  launch { scopeA() }
  launch { scopeB() }
}

suspend fun scopeA = coroutineScope { /* some work */ }
suspend fun scopeB = coroutineScope { /* some work */ }
d
That was my initial idea, but I can't get my coroutine to restart when resuming. I know I'd need to post more relevant code to maybe get somewhere though. Appreciate your help
k
If you give some more relevant hints I’m willing to help you take a stab at it
d
Okay. Just saw you're an Android dev too so I think I can. I have a nested fragment from a 3rd party library whose
lifecycleScope
I'm currently using to communicate changes from the parent UI/ViewModel with
Flow
. This nested fragment must be able to survive configuration changes. Since it's nested, I need to stop propagating events to it when the parent UI get's torn down and recreated, so I want to use
viewLifecycleOwner
. The fragment survives configuration changes but it can also be torn down and replaced with a new one before a configuration change ever happens, hence my use case where it's
lifecycleScope
could outlive the current
viewLifecycleOwner
, but it also may not. In that case, the old Fragment actually get's leaked when we use the
viewLifecycleOwner.lifecycleScope
to observe the changes and then it crashes. I know I could just use the
Job
that gets returned from the
launch
method, but I wanted to ask anyways if this was possible by "combining" coroutine scopes and catering to the lowest common denominator
k
OOOOOOOF unfortunately almost all of my knowledge of fragments has atrophied (thankfully). We don’t use
lifecycleScope
at all. I fear I won’t be of much help.
d
lol no worries. If this 3rd party library provided a custom view instead of a Fragment I'm sure this would be smoother sailing. Thanks anyways though, I really appreciate it
g
There is no out-of-the-box way to combine coroutine scopes, only by using the same Job() for them, but in this case it’s unclear why even create 2 scopes. Just use Job instance to cancel
But I feel something wrong with hierarchy of licycles in your case
I have a nested fragment from a 3rd party library whose
lifecycleScope
I’m currently using to communicate changes from the parent UI/ViewModel with
Flow
This part sounds strange for me, why would you use lifecycle of another fragment?