#lazy-evaluation #lazy-static #async #once-cell #static #tokio

async-lazy

A value which is initialized on the first access, with an async function

1 unstable release

0.1.0 May 18, 2023

#804 in Asynchronous

Download history 29/week @ 2024-03-11 19/week @ 2024-03-18 31/week @ 2024-03-25 61/week @ 2024-04-01 26/week @ 2024-04-08 65/week @ 2024-04-15 64/week @ 2024-04-22 48/week @ 2024-04-29 25/week @ 2024-05-06 21/week @ 2024-05-13 37/week @ 2024-05-20 24/week @ 2024-05-27 25/week @ 2024-06-03 95/week @ 2024-06-10 14/week @ 2024-06-17 38/week @ 2024-06-24

173 downloads per month
Used in 5 crates (4 directly)

MIT/Apache

25KB
354 lines

async-lazy

Build Status Crates.io API reference License

An async version of once_cell::sync::Lazy, std::sync::OnceLock or lazy_static. Uses tokio's sychronization primitives.

Crate features

  • parking_lot: Enables the corresponding feature in tokio, and ssallows constructing Lazys in const contexts.
  • nightly: Uses nightly Rust features to implement IntoFuture for references to Lazys, obviating the need to call force().

Example

use std::time::Duration;
use async_lazy::Lazy;

async fn some_computation() -> u32 {
    tokio::time::sleep(Duration::from_secs(1)).await;
    1 + 1
}

static LAZY : Lazy<u32> = Lazy::const_new(|| Box::pin(async { some_computation().await }));

#[tokio::main]
async fn main() {
    let result = tokio::spawn(async {
        *LAZY.force().await
    }).await.unwrap();

    assert_eq!(result, 2);
}

Dependencies

~2–8MB
~49K SLoC