#lazy-evaluation #once-cell #lazy-static #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

#303 in Asynchronous

Download history 50/week @ 2024-12-02 97/week @ 2024-12-09 42/week @ 2024-12-16 32/week @ 2025-01-06 57/week @ 2025-01-13 54/week @ 2025-01-20 37/week @ 2025-01-27 44/week @ 2025-02-03 94/week @ 2025-02-10 166/week @ 2025-02-17 389/week @ 2025-02-24 156/week @ 2025-03-03 90/week @ 2025-03-10 39/week @ 2025-03-17

748 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

~2–7.5MB
~47K SLoC