#once-cell #lazy-evaluation

async-lazy

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

1 unstable release

0.1.0 May 18, 2023

#743 in Asynchronous

Download history 32/week @ 2024-07-20 29/week @ 2024-07-27 103/week @ 2024-08-03 81/week @ 2024-08-10 144/week @ 2024-08-17 59/week @ 2024-08-24 70/week @ 2024-08-31 19/week @ 2024-09-07 11/week @ 2024-09-14 31/week @ 2024-09-21 32/week @ 2024-09-28 289/week @ 2024-10-05 369/week @ 2024-10-12 362/week @ 2024-10-19 177/week @ 2024-10-26 43/week @ 2024-11-02

1,048 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–7.5MB
~49K SLoC