https://kotlinlang.org logo
#coroutines
Title
# coroutines
b

bod

04/04/2020, 3:17 PM
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

Dominaezzz

04/04/2020, 4:14 PM
The first
resume
needs an import I think. (It's an extension function).
b

bod

04/04/2020, 4:23 PM
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

Orhan Tozan

04/04/2020, 10:25 PM
I thought that if you dont need the cancellation exception, you use
suspendCoroutine
instead of
suspendCancellableCoroutine
?
d

Dominaezzz

04/04/2020, 10:53 PM
Yes. I assume that
cont.invokeOnCancellation
is being used.
b

bod

04/04/2020, 11:02 PM
turns out I was using
suspendCancellableCoroutine
when I could use
suspendCoroutine
🙂 Thanks a lot
l

louiscad

04/05/2020, 10:09 PM
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

Orhan Tozan

04/06/2020, 1:35 PM
With supporting cancellation, do you mean passing something like
removeEventListener
to the onCancellation?
l

louiscad

04/06/2020, 1:52 PM
@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
2 Views