tokio-rs / tokio

A runtime for writing reliable asynchronous applications with Rust. Provides I/O, networking, scheduling, timers, ...
https://tokio.rs
MIT License
26.59k stars 2.45k forks source link

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

Closed jwodder closed 3 months ago

jwodder commented 4 months ago

(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 */
}
Darksonn commented 4 months ago

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