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

deviant

03/20/2017, 9:17 AM
Copy code
launch(context + job1 + job2){}
is it possible to use 2 different parents to control child lifecycle? well, i know it's not. but what best way to achieve such functionality?
k

kirillrakhman

03/20/2017, 9:30 AM
I guess you could start two separate couroutines, join them to the parent jobs. and when one of them terminates, cancel the child
d

deviant

03/20/2017, 9:33 AM
i want to use job1 and job2 just for cancellation signal for the 1 child. job1 take care of activity lifecycle (cancel on onStop) and job2 is some hand made control for the childs using it.
k

kirillrakhman

03/20/2017, 9:34 AM
maybe use
invokeOnCompletion
?
d

deviant

03/20/2017, 9:34 AM
i think its better to use actor model with cancellation event
k

kirillrakhman

03/20/2017, 9:34 AM
and check if the exception is a
CancellationException
d

deviant

03/20/2017, 9:36 AM
maybe use
invokeOnCompletion
?
afraid to drown in boilerplate 🙂
h

hackerham

03/20/2017, 9:59 AM
why not create two contexts?
one will be suspended indefinitely, the other will work
if you cancel first job, second will be cancelled too
that will work two ways 1. you can use two "async" to create jobs, one will be parent of another 2. you can create two jobs, parent and child, manually and then pass it to launch
d

deviant

03/20/2017, 10:14 AM
could you please show simple code example? not sure i understood correctly.
h

hackerham

03/20/2017, 11:23 AM
Copy code
var job2 = null;
val job1 = async(start=true) {
   job2 = async(start=true) {
      //do stuff
   }
   job2.onComplete { job1.cancel() }
   suspendCoroutine<Unit> { cont -> /* it never ends BWAHHAHA */ }
}
something like that
the idea is that job1.cancel() also cancels job2 because they are related
d

deviant

03/20/2017, 1:16 PM
thanks, Ivan. this nesting job1->job2 looks not very flexible though
anyway i've managed my task with 1 parent job instead of 2
h

hackerham

03/20/2017, 1:51 PM
I'm happy for you 🙂
3 Views