Hi, if I have two existing scopes and want to laun...
# coroutines
l
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
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
Not very elegant but I've tried it and works, thank you!
i
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
Yes thank you! I've created a similar extension function in my code