<@U2E974ELT> given that using a job is the idiomat...
# coroutines
k
@elizarov given that using a job is the idiomatic approach to cancelling all running coroutines when a component is being destroyed, for instance. Should there be a method to cancel all child jobs but keep the parent job alive? Something like
clear
and
cancel
on a composite disposable in Rx I have a situation where the parent job should live longer than it's children.
1
e
How much longer? Like a little bit longer, or you have a permanently running parent job?
k
A little bit longer
e
You can use
run(NonCancellable) { ... }
for bits of code that need to be running despite the fact the job was cancelled. Also, cancellation only affects suspending functions (cancellable suspending functions, to be precise), so if you are just cleaning up some data-structures or resetting some flags, none of that is going to be cancelled.
Remember: cancellation is fully cooperative.
k
Hmm. Okay. So, I can use
NonCancellable
instead of a simple
Job()
as the parent. Does calling cancel on it cancel it's children, while itself remains at large?
e
You'll have to explicitly create a separate
Job
and pass its instance in the context of each child you start. That way you can cancel this job, while leaving the parent coroutine alone.
d
i think @kingsley means case when Activity goes to background:
Copy code
fun onStop(){
 job.cancel()// it would be nice to iterate through child jobs somehow and cancel them instead of cancelling parent
}
and when activity returns back to foreground we need to recreate the parent job because it was already cancelled
k
@elizarov yes, I'm currently doing that. A little context: I have a parent job that exists throughout the instance of a component (fragment), however, I need to cancel all child jobs in onDestroyView. The parent job should still be available for use when the view gets recreated within the same fragment instance.
k
Why not just recreate everything? It's just one more object.
k
@kenkyee you mean shorten the lifespan of the parent (and dependent services) and recreate them Everytime the view is recreated?
k
Yes... Create the parent in the create every time
k
Yea well. I'm resorting to that. I hoped there might be a better way