-
Notifications
You must be signed in to change notification settings - Fork 1.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature Request: invokeOnCompletion handler for suspendCancellableCoroutine #3065
Comments
Note that you could define your callback as an object instead of a lambda to get access to val callback = object : (Int) -> Unit {
override fun invoke(value: Int) {
someApi.unregisterCallback(this)
cont.resume(value)
}
} But the argument about repeating code still holds though. |
@jschools Thinking about this, why would you wrap those APIs into suspend functions, though? Looks like a If you just want the first event from those APIs, then simply call |
@joffrey-bion I was thinking it would be convenient for I agree |
They solve different problems, though.
Yeah, if some SDKs take a single-shot callback that needs to be explicitly unregistered, it's pretty crappy indeed. But when this happens there are options, like the above.
I'm not opposed to this addition, though, don't get me wrong. Also I am by no means of any authority in this repository 😄 I'll let the maintainers decide for themselves |
Actually, you can use |
@LouisCAD I think it would not be very convenient to do with a |
It is inconvenient to use
suspendCancellableCoroutine
to wrap an API that requires a callback to be unregistered after receiving the call. Examples include "event bus" or "broadcast" APIs which do not unregister a callback automatically and will leak the callback.We have
invokeOnCancellation
to handle situations where the coroutine is cancelled, although there is no handler for when the continuation is resumed successfully. This potentially could be done in the callback itself prior to callingcont.resume()
, but it is not possible to get a reference to the callback if it is a lambda. It may also duplicate the code in theinvokeOnCancellation
block.For example:
I propose adding
invokeOnCompletion
toCancelableContinuation
which could be used to handle both cancellation and successful resume, similar toJob.invokeOnCompletion
.If there is a simpler way around this that I am missing, please do let me know.
The text was updated successfully, but these errors were encountered: