Crate async_cancellation_token

Crate async_cancellation_token 

Source
Expand description

§async-cancellation-token

async-cancellation-token is a lightweight single-threaded Rust library that provides cancellation tokens for cooperative cancellation of asynchronous tasks and callbacks.

This crate works in single-threaded async environments (e.g., futures::executor::LocalPool) and uses Rc, Cell, and RefCell internally. It is not thread-safe.

§Example

use std::time::Duration;
use async_cancellation_token::CancellationTokenSource;
use futures::{FutureExt, executor::LocalPool, pin_mut, select, task::LocalSpawnExt};
use futures_timer::Delay;

let cts = CancellationTokenSource::new();
let token = cts.token();

let mut pool = LocalPool::new();
let spawner = pool.spawner();

spawner.spawn_local(async move {
    for i in 1..=5 {
        let delay = Delay::new(Duration::from_millis(100)).fuse();
        let cancelled = token.cancelled().fuse();
        pin_mut!(delay, cancelled);

        select! {
            _ = delay => println!("Step {i}"),
            _ = cancelled => {
                println!("Cancelled!");
                break;
            }
        }
    }
}.map(|_| ())).unwrap();

spawner.spawn_local(async move {
    Delay::new(Duration::from_millis(250)).await;
    cts.cancel();
}.map(|_| ())).unwrap();

pool.run();

Structs§

CancellationToken
A token that can be checked for cancellation or awaited.
CancellationTokenSource
A source that can cancel associated CancellationTokens.
Cancelled
Error returned when a cancelled token is checked synchronously.
CancelledFuture
Future that completes when a CancellationToken is cancelled.