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

kingsley

03/18/2017, 4:32 PM
@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

elizarov

03/18/2017, 4:34 PM
How much longer? Like a little bit longer, or you have a permanently running parent job?
k

kingsley

03/18/2017, 4:38 PM
A little bit longer
e

elizarov

03/18/2017, 4:41 PM
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

kingsley

03/18/2017, 4:48 PM
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

elizarov

03/18/2017, 6:38 PM
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

deviant

03/18/2017, 6:55 PM
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

kingsley

03/18/2017, 7:35 PM
@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

kenkyee

03/19/2017, 12:14 PM
Why not just recreate everything? It's just one more object.
k

kingsley

03/19/2017, 1:19 PM
@kenkyee you mean shorten the lifespan of the parent (and dependent services) and recreate them Everytime the view is recreated?
k

kenkyee

03/19/2017, 1:20 PM
Yes... Create the parent in the create every time
k

kingsley

03/19/2017, 2:45 PM
Yea well. I'm resorting to that. I hoped there might be a better way
2 Views