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

Add a CancellationToken method for running a future until completion or cancellation #6566

Open
jwodder opened this issue May 16, 2024 · 1 comment
Labels
A-tokio-util Area: The tokio-util crate C-feature-request Category: A feature request. M-sync Module: tokio/sync

Comments

@jwodder
Copy link

jwodder commented May 16, 2024

(This is a variant of the idea proposed in #4598; I was advised to create a new issue for this.)

Give how (seemingly) often a tokio_util::sync::CancellationToken gets used as follows:

tokio::select! {
  _ = token.cancelled() => { /* something */ }
  other => other_future => { /* something else */ }
}

I propose adding a method to CancellationToken that takes a Future, runs it to completion, and returns its output — unless the token is cancelled before the future completes, in which case the future is dropped. I feel the best type for the result of this composed future would be an Option<Fut::Output>, with None indicating cancellation.

Example usage of this new method (here called run_until_cancelled()):

if let Some(r) = token.run_until_cancelled(fut).await {
     /* Future completed; do stuff with future's return value `r` */
} else {
     /* Token & future were cancelled; do stuff for that */
}
@jwodder jwodder added A-tokio Area: The main tokio crate C-feature-request Category: A feature request. labels May 16, 2024
@Darksonn Darksonn added A-tokio-util Area: The tokio-util crate M-sync Module: tokio/sync and removed A-tokio Area: The main tokio crate labels May 17, 2024
@Darksonn
Copy link
Contributor

Seems reasonable enough to me. It is nice that it does not involve a FutureExt trait, which I prefer to avoid.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-tokio-util Area: The tokio-util crate C-feature-request Category: A feature request. M-sync Module: tokio/sync
Projects
None yet
Development

No branches or pull requests

2 participants