#future #tokio #task #prevent #shield #wrapping #aborted

tokio-shield

Prevent futures from being aborted by wrapping them in tasks

2 releases

0.1.1 Sep 20, 2023
0.1.0 May 25, 2023

#1847 in Asynchronous

Download history 11/week @ 2024-10-09 26/week @ 2024-10-16 18/week @ 2024-10-23 61/week @ 2024-10-30 46/week @ 2024-11-06 31/week @ 2024-11-13 79/week @ 2024-11-20 57/week @ 2024-11-27 36/week @ 2024-12-04 45/week @ 2024-12-11 39/week @ 2024-12-18 17/week @ 2024-12-25 15/week @ 2025-01-01 46/week @ 2025-01-08 24/week @ 2025-01-15 22/week @ 2025-01-22

109 downloads per month
Used in poem-ext

MIT license

7KB
71 lines

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);
}

Dependencies

~2.6–8.5MB
~62K SLoC