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

async-lazy

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

3 releases

0.1.2 Feb 23, 2025
0.1.1 Feb 23, 2025
0.1.0 May 18, 2023

#545 in Asynchronous

Download history 399/week @ 2025-07-16 510/week @ 2025-07-23 640/week @ 2025-07-30 450/week @ 2025-08-06 410/week @ 2025-08-13 585/week @ 2025-08-20 618/week @ 2025-08-27 450/week @ 2025-09-03 352/week @ 2025-09-10 450/week @ 2025-09-17 474/week @ 2025-09-24 470/week @ 2025-10-01 582/week @ 2025-10-08 590/week @ 2025-10-15 305/week @ 2025-10-22 305/week @ 2025-10-29

1,868 downloads per month
Used in 5 crates

MIT/Apache

25KB
348 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.

This crate offers an API similar to the Lazy type from async-once-cell crate. The difference is that this crate's Lazy accepts an FnOnce() -> impl Future instead of a Future, which makes use in statics easier.

Crate features

  • 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::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

~1.8–5MB
~80K SLoC