mzgreen
03/01/2022, 11:23 AMCompletableDeferred 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?Sam
03/01/2022, 11:31 AMsuspendCancellableCoroutine. It's more lightweight, and it's also specifically designed for handling cancellation properly via continuation.invokeOnCancellation.Sam
03/01/2022, 11:32 AMCompletableDeferred, I don't think the InstallReferrerClient connection will be cancelled when the coroutine is cancelled.Sam
03/01/2022, 11:32 AMsuspendCancellableCoroutine, you see this code:
// If the coroutine is cancelled, remove the listener
cont.invokeOnCancellation { removeOnLayoutChangeListener(listener) }Sam
03/01/2022, 11:33 AMCompletableDeferred.invokeOnCompletion, but it wouldn't be as cleanmzgreen
03/01/2022, 11:58 AMSam
03/01/2022, 12:08 PMsuspendCancellableCoroutine 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 optionSam
03/01/2022, 12:09 PMsuspendCancellableCoroutineephemient
03/02/2022, 12:44 AMephemient
03/02/2022, 12:44 AM