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

async-lazy

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

1 unstable release

0.1.0 May 18, 2023

#769 in Asynchronous

Download history 10/week @ 2024-01-08 62/week @ 2024-01-22 42/week @ 2024-01-29 20/week @ 2024-02-05 15/week @ 2024-02-12 46/week @ 2024-02-19 38/week @ 2024-02-26 50/week @ 2024-03-04 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

185 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–9.5MB
~48K SLoC