Skip to content

Feature Request: invokeOnCompletion handler for suspendCancellableCoroutine #3065

Open
@jschools

Description

@jschools

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 calling cont.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 the invokeOnCancellation block.

For example:

suspendCancellableCoroutine<Int> { cont ->
  val callback: (Int) -> Unit = {
    someApi.unregisterCallback(???) // no way to get reference to a lambda - cannot use `this` or `callback`
    cont.resume(it)
  }
  
  someApi.registerCallback(callback)
  
  cont.invokeOnCancellation {
    // not called after successful resume!
    someApi.unregisterCallback(callback)
  }
}

I propose adding invokeOnCompletion to CancelableContinuation which could be used to handle both cancellation and successful resume, similar to Job.invokeOnCompletion.

If there is a simpler way around this that I am missing, please do let me know.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions