Edoardo Luppi
08/04/2024, 2:54 PMCancellableContinuation.tryResume
is marked as internal API.
Have you ever had to use it?
I have a callback that might fire multiple times, but obviously the continuation must be resumed only once.
Does that look like a legitimate use case?
Note that I can't get rid of the callback, I still need it for future calls, I just don't want to resume obviously.Joffrey
08/04/2024, 2:56 PMcallbackFlow
insteadEdoardo Luppi
08/04/2024, 3:13 PMerror
callback during a suspend fun connect
call, to connect to a socket.
The error
callback can be called instead of connected
, if connection fails, but also afterwards for any network error, for example.Daniel Pitts
08/04/2024, 4:04 PMEdoardo Luppi
08/04/2024, 4:08 PMsuspendCancellableCoroutine
block.Daniel Pitts
08/04/2024, 4:09 PMDaniel Pitts
08/04/2024, 4:09 PM* Suspends the coroutine like [suspendCoroutine], but providing a [CancellableContinuation] to
* the [block]. This function throws a [CancellationException] if the [Job] of the coroutine is
* cancelled or completed while it is suspended.
*
* A typical use of this function is to suspend a coroutine while waiting for a result
* from a single-shot callback API and to return the result to the caller.
* For multi-shot callback APIs see [callbackFlow][kotlinx.coroutines.flow.callbackFlow].
Edoardo Luppi
08/04/2024, 4:13 PMFlow
, for my use case it's not compatible with the API I want to expose.Daniel Pitts
08/04/2024, 4:14 PMEdoardo Luppi
08/04/2024, 4:15 PMDaniel Pitts
08/04/2024, 4:15 PMDaniel Pitts
08/04/2024, 4:26 PMfun callbackApi(callback: () -> Unit) {
repeat(3) {
callback()
}
}
suspend fun connect() {
suspendCancellableCoroutine {
val once = lazy { it.resume(Unit) }
callbackApi { once.value }
}
}
Rick Clephas
08/05/2024, 5:29 AMRick Clephas
08/05/2024, 5:34 AMEdoardo Luppi
08/05/2024, 8:30 AMcontinuation.isActive
.
If it isn't active, it means it's been cancelled or completed already (normally or with an exception).Dmitry Khalanskiy [JB]
08/05/2024, 9:23 AMresume
, and you have code like this
if (isActive) {
// line X
resume(Unit)
}
then the coroutine could have been resumed while this thread executes line X.Edoardo Luppi
08/05/2024, 9:25 AMtryResume
calls?Dmitry Khalanskiy [JB]
08/05/2024, 9:30 AMInternalCoroutinesApi
unless we have your project in our CI. We can (and sometimes do) remove, rename, edit these API entry points with no concern for backward compatibility. tryResume
is an implementation detail that may change at any point.Edoardo Luppi
08/05/2024, 9:33 AMtry*
functions.
https://github.com/Kotlin/kotlinx.coroutines/issues/48
Looks like I'm not alone in this kind of problem.Dmitry Khalanskiy [JB]
08/05/2024, 12:30 PM===
) each time?Edoardo Luppi
08/05/2024, 12:33 PMEdoardo Luppi
08/05/2024, 12:34 PMEdoardo Luppi
08/05/2024, 12:36 PMDmitry Khalanskiy [JB]
08/05/2024, 12:37 PM