when adapting a callback API to suspending is ther...
# coroutines
k
when adapting a callback API to suspending is there any point in using
suspendCancellableCoroutine
instead of
suspendCoroutine
when there is no way to propagate cancellation to the adapted API and no action to run via
CancellableContinuation::invokeOnCancellation
?
g
There is no reason to use cancellable coroutine
👍 2
b
I would advocate for cancellable coroutine in some cases, because
suspendCoroutine
makes your code non-cooperative to cancellation (even assuming you can't propagate cancellation to adapted API). Also adapter API must eventually completes (either successfully or exceptionally), otherwise caller scope will never transits to terminal state (it may lead to leaking resources that supposed to be closed via
job.invokeOnCompletion
).
to summarize: 1. If it's important for your business logic to await for result (idk, maybe something like payment API - you don't want to cancel it in the middle) - use
suspendCoroutine
2. If you want this fun to behave like "it's support cancellation" - use
suspendCancellableCoroutine
3. If you don't trust the API too much, or if you know that it may never complete - use
suspendCancellableCoroutine
4. otherwise you can use
suspendCoroutine
👍 2