Skip to content
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] Add awaitCancellation() #2213

Closed
LouisCAD opened this issue Aug 24, 2020 · 2 comments
Closed

[Feature request] Add awaitCancellation() #2213

LouisCAD opened this issue Aug 24, 2020 · 2 comments

Comments

@LouisCAD
Copy link
Contributor

I can submit a PR.

Use case examples

With try/finally:

suspend fun showStuffUntilCancelled(data: Stuff): Nothing {
    try {
        someSubView.text = data.title
        anotherSubView.text = data.description
        someView.isVisible = true
        awaitCancellation() // Suspends so the view stays visible
    } finally {
        someView.isVisible = false // Called on cancellation, cannot forget to hide the view!
    }
}

With an inline higher order function:

suspend fun showStuffUntilCancelled(data: Stuff): Nothing {
    someSubView.text = data.title
    anotherSubView.text = data.description
    someView.visibleInScope {
        awaitCancellation() // Suspends so the view stays visible
    }
}

Implementation

import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.suspendCancellableCoroutine

/**
 * Suspends until cancellation, in which case it will throw a [CancellationException].
 *
 * Handy because it returns [Nothing], allowing it to be used in any coroutine,
 * regardless of the required return type.
 */
suspend inline fun awaitCancellation(): Nothing = suspendCancellableCoroutine {}
@elizarov
Copy link
Contributor

Good stuff. PR is welcome.

LouisCAD added a commit to LouisCAD/kotlinx.coroutines that referenced this issue Sep 2, 2020
recheej pushed a commit to recheej/kotlinx.coroutines that referenced this issue Dec 28, 2020
recheej pushed a commit to recheej/kotlinx.coroutines that referenced this issue Dec 28, 2020
@LouisCAD
Copy link
Contributor Author

Hello, I just wanted to thank you for letting this in kotlinx.coroutines, I use it very often, as you can see:
Screenshot 2022-01-20 at 12 32 59

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants