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

Sergey

11/30/2023, 6:43 PM
Hey there! What are my options if I want to retain parent-child relationship in terms of making parent wait for children completion when
parent.join()
is invoked but prevent propagation of a cancellations from parent to children i.e. let children complete on it’s own without interruptions when
parent.cancel() / parent.cancelAndJoin()
is invoked? I create children using
async {}
blocks i.e.
Copy code
val parent = CoroutineScope(dispatcher).launch { 
...
    val childRes0 = async { ... }
    val childRes1 = async { ... }
...
}

...

parent.cancelAndJoin()
k

kevin.cianfarini

11/30/2023, 6:52 PM
Wrap the children in
NonCancellable
?
s

Sergey

11/30/2023, 7:01 PM
Thanks Kevin, I’m reading what internet has on
NonCancellable
right now. I believe I have to adapt my code to something like
Copy code
val parent = CoroutineScope(dispatcher).launch { 
...
withConttext(NonCancellable) {
    val childRes0 = async { ... }
    val childRes1 = async { ... }
}
...
}

...

parent.cancelAndJoin()
what if my children are created in dedicated
coroutineScope
like
Copy code
fun runManyChildren() = coroutineScope {
    vals.map { x -> async { .... } }
}

val parent = CoroutineScope(dispatcher).launch { 
...
withConttext(NonCancellable) {
    runManyChildren()
}
...
}

...

parent.cancelAndJoin()
Will
runManyChildren
be uncancellable in this case?
k

kevin.cianfarini

11/30/2023, 7:03 PM
yup
s

Sergey

11/30/2023, 7:04 PM
Got it, thanks for your help!
k

kevin.cianfarini

11/30/2023, 7:08 PM
No problem!
u

uli

12/01/2023, 9:03 AM
be aware though, that even the canceled parent will only terminate after all children completed
s

Sergey

12/01/2023, 10:38 AM
Thanks Uli, that’s the desired behaviour in my case.
👍 1
2 Views