pub fn with_stop<T: Send + 'static, TFuture: Future<Output = T> + Send + 'static>(
original_future: TFuture,
) -> (Box<dyn FnOnce() -> Result<()> + Send>, Pin<Box<dyn Future<Output = Option<T>> + Send + 'static>>)Expand description
Wrap a future into one that can be stopped at any given
moment by invoking a returned stop function.
Wraps the original result of a future into an Option to
indicate if the future completed (Some(original result)) or
was stopped explicitelly (None).
ยงExamples
use std::pin::Pin;
use futures::{future, Future};
use cs_utils::futures::{wait, with_stop};
#[tokio::main]
async fn main() {
// as future that never completes
let forever_future = async move {
loop {
wait(5).await;
}
};
// wrap the original future to get the `stop` function
let (stop, forever_future) = with_stop(forever_future);
// create futures for testing purposes
let futures: Vec<Pin<Box<dyn Future<Output = ()>>>> = vec![
Box::pin(async move {
// run the forever future
let result = forever_future.await;
assert!(
result.is_none(),
"Must complete with `None` result since it was stopped prematurely.",
);
}),
Box::pin(async move {
wait(25).await;
// stop the forever future
stop()
.expect("Cannot stop the future.");
// wait for some more time so the assertion in
// the boxed future above has a chance to run
wait(25).await;
}),
];
// race the futures to completion
future::select_all(futures).await;
}