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

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

#321 in Asynchronous

Download history 109/week @ 2024-11-14 141/week @ 2024-11-21 83/week @ 2024-11-28 65/week @ 2024-12-05 70/week @ 2024-12-12 19/week @ 2024-12-19 5/week @ 2025-01-02 45/week @ 2025-01-09 67/week @ 2025-01-16 38/week @ 2025-01-23 41/week @ 2025-01-30 66/week @ 2025-02-06 85/week @ 2025-02-13 396/week @ 2025-02-20 198/week @ 2025-02-27

749 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