Hi, if I have two existing scopes and want to launch a coroutine that cancel if any of the two scopes is cancelled, how can I do it?
i
Icaro Temponi
08/01/2019, 11:43 AM
Launch the coroutine using the first scope and add a completion listener to the second scope to cancel the job, maybe there's another way, but this should do, I just don't know if the child.cancel() throws if the job is already cancelled
Copy code
val parent1 = CoroutineScope(Job())
val parent2 = CoroutineScope(Job())
val child = parent1.launch {
//Do something
} parent2.coroutineContext[Job]?.invokeOnCompletion { child.cancel() }
l
Lorenzo Testa
08/01/2019, 11:52 AM
Not very elegant but I've tried it and works, thank you!
i
Icaro Temponi
08/01/2019, 4:33 PM
For a better looking api, you could add this function:
Copy code
fun Job.addTo(parent: CoroutineScope): Job {
val job = parent.coroutineContext[Job]
job?.invokeOnCompletion { this.cancel() }
return this
}
then run:
Copy code
parent1
.launch { //Do something }
.addTo(parent2)
.addTo(parent3) //Add to as many parents as you want
l
Lorenzo Testa
08/01/2019, 4:52 PM
Yes thank you! I've created a similar extension function in my code