Hello, World! When using `suspendCancellableCorou...
# coroutines
b
Hello, World! When using
suspendCancellableCoroutine
I sometimes see code that calls
cont.resume(result)
but when I try that, it's looking for a
onCancellation
argument, I so I need to do
cont.resume(result) {}
instead. Ideas why? (May be relevant: I'm in Kotlin-js).
d
The first
resume
needs an import I think. (It's an extension function).
b
Thought of it but couldn't find the right one, and IJ didn't help. But I finally found it:
Copy code
import kotlin.coroutines.resume
😄 Thanks!
o
I thought that if you dont need the cancellation exception, you use
suspendCoroutine
instead of
suspendCancellableCoroutine
?
d
Yes. I assume that
cont.invokeOnCancellation
is being used.
b
turns out I was using
suspendCancellableCoroutine
when I could use
suspendCoroutine
🙂 Thanks a lot
l
Well,
suspendCoroutine
is when you cannot and don't want to support cancellation at all, which can lead to memory leaks in some cases if your code never resumes or resumes after a long time while it should have been cancelled.
So, I tend to think the opposite scenario is more correct: one might use
suspendCoroutine
when
suspendCancellableCoroutine
could/should be used.
👍 1
o
With supporting cancellation, do you mean passing something like
removeEventListener
to the onCancellation?
l
@Orhan Tozan There's multiple ways of doing it. You mentioned one way to do it. Basically, you need to unregister or cancel the callback, and do it from
onCancellation
or in a `try`/`finally` or `try`/`catch(e: CancellationException)` block surrounding the
suspendCancellableCoroutine
call. Here's a real world example that allows to wait for a click on a
View
in an Android app: https://github.com/LouisCAD/Splitties/blob/49e2ee566730aaeb14b4fa9e395a677c3f214dba/modules/views-coroutines/src/androidMain/kotlin/splitties/views/coroutines/VisibilityAndClicks.kt#L34-L51