Hi guys, Is CompletableDeferred’s await method coo...
# coroutines
n
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
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
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
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
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
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
That might actually work. I guess I never though of it that way. Thanks man!
a
n
Great success! 😄