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

Nemanja Scepanovic

09/28/2020, 7:55 AM
Hi guys, Is CompletableDeferred’s await method cooperative, meaning if wrapping context gets
CanellationException
would this completable deferred’s job be automatically completed or not? If not, what is the best way of making it cooperative? Thanks 🙂
d

Daniele Segato

09/28/2020, 9:16 AM
a cancellation is propagated to children. so when you cancel a parent of the scope used to create the deferred that is cancellated to. your
await()
will receive a cancellation exception if that happens. I'm not sure if I answered your question
n

Nemanja Scepanovic

09/28/2020, 10:02 AM
Hmm, but the if onCompletion{} is set, why isn’t it being invoked after cancellation is propagated? Shouldn’t completableDeferred object’s state become COMPLETED when parent’s cancellation exception is propagated? Or i misinterpreted how onCompleted{} behaves?
a

araqnid

09/28/2020, 10:47 AM
CompletableDeferred isn’t automatically linked to a Job. A Deferred that is implemented by async{} will complete exceptionally if the async coroutine is cancelled, but a CompletableDeferred needs to be completed explicitly. So when you say “wrapping context”, how is this being linked to the CompletableDeferred? Are you creating it with a parent explicitly?
n

Nemanja Scepanovic

09/28/2020, 10:49 AM
By wrapping context I meant viewModelScope inside which completableDeferred logic is called (this is just a simplification but you get the point).
Ok, so only if completableDeferred is completed explicitly though
complete
or
completeExceptionally
will the
invokeOnCompletion
be called?
a

araqnid

09/28/2020, 10:52 AM
I believe so, and I presume that if you link the CompletableDeferred to a parent Job (
CompletableDeferred(parent=coroutineContext[Job]!!)
), then the parent job being cancelled will automatically complete it with CancellationException
n

Nemanja Scepanovic

09/28/2020, 11:04 AM
That might actually work. I guess I never though of it that way. Thanks man!
a

araqnid

09/28/2020, 11:04 AM
n

Nemanja Scepanovic

09/28/2020, 11:05 AM
Great success! 😄
7 Views