Crate async_singleflight[][src]

A singleflight implementation for tokio.

Inspired by singleflight.

Examples

use futures::future::join_all;
use std::sync::Arc;
use std::time::Duration;

use anyhow::Result;
use async_singleflight::Group;

const RES: usize = 7;

async fn expensive_fn() -> Result<usize> {
    tokio::time::sleep(Duration::new(1, 500)).await;
    Ok(RES)
}

#[tokio::main]
async fn main() {
    let g = Arc::new(Group::new());
    let mut handlers = Vec::new();
    for _ in 0..10 {
        let g = g.clone();
        handlers.push(tokio::spawn(async move {
            let res = g.work("key", expensive_fn).await;
            let r = res.as_ref().as_ref().unwrap();
            println!("{}", r);
        }));
    }

    join_all(handlers).await;
}

Structs

Group

Group represents a class of work and creates a space in which units of work can be executed with duplicate suppression.