tokio-shield

Crates.iotokio-shield
lib.rstokio-shield
version0.1.1
sourcesrc
created_at2023-05-25 15:53:09.170382
updated_at2023-09-20 08:53:28.166791
descriptionPrevent futures from being aborted by wrapping them in tasks
homepage
repositoryhttps://github.com/Defelo/tokio-shield
max_upload_size
id874367
size11,893
Felix Bargfeldt (Defelo)

documentation

https://docs.rs/tokio-shield/

README

check test codecov Version dependency status

tokio-shield

Prevent futures in Rust from being aborted by wrapping them in tasks.

Example

use std::time::Duration;
use tokio::{sync::oneshot, time::sleep};
use tokio_shield::Shield;

#[tokio::main]
async fn main() {
    let (tx, mut rx) = oneshot::channel();

    // Create and shield a future that waits for 10ms and then returns a value
    // via a oneshot channel.
    let future = async {
        sleep(Duration::from_millis(10)).await;
        tx.send(42).unwrap();
    }.shield();

    // Spawn a task to run this future, but cancel it after 5ms.
    let task = tokio::spawn(future);
    sleep(Duration::from_millis(5)).await;
    task.abort();
    sleep(Duration::from_millis(5)).await;

    // After 10ms the value can successfully be read from the oneshot channel,
    // because `shield` prevented our future from being canceled.
    assert_eq!(rx.try_recv().unwrap(), 42);
}
Commit count: 31

cargo fmt