How do I choose between `CompletableDeferred` and ...
# coroutines
m
How do I choose between
CompletableDeferred
and
suspendCancellableCoroutine
when wrapping a callback based API into a coroutines API? Here is an example of an API wrapped using `CompletableDeferred`: https://handstandsam.com/2022/02/28/install-referrer-kotlin-extension/ And here are examples of APIs wrapped using `suspendCancellableCoroutine`: https://chris.banes.dev/suspending-views/ When is the one approach preferable over the other one?
s
I would always recommend using
suspendCancellableCoroutine
. It's more lightweight, and it's also specifically designed for handling cancellation properly via
continuation.invokeOnCancellation
.
✔️ 1
1
In the example that you shared using
CompletableDeferred
, I don't think the
InstallReferrerClient
connection will be cancelled when the coroutine is cancelled.
Whereas in the example with
suspendCancellableCoroutine
, you see this code:
Copy code
// If the coroutine is cancelled, remove the listener
cont.invokeOnCancellation { removeOnLayoutChangeListener(listener) }
You probably could achieve something similar using
CompletableDeferred.invokeOnCompletion
, but it wouldn't be as clean
m
Thank you. Is there a way to check which one is "more lightweight" without knowing the internals?
s
suspendCancellableCoroutine
is really the "primitive" on top of which all "await"-style suspending operations are built, so you can assume that using it directly is always the most lightweight option
👍 1
In fact CompletableDeferred.await itself will end up calling something very similar to
suspendCancellableCoroutine
🙏 1
e
(it doesn't, it goes lower level than that)
👍 1
suspendCoroutine is probably the lowest level primitive that a user should typically see
500 Views