#lazy #static #async

async-once-cell

Async single assignment cells and lazy values

5 releases (3 breaking)

new 0.4.0 May 14, 2022
0.3.1 May 11, 2022
0.3.0 Aug 11, 2021
0.2.0 Aug 10, 2021
0.1.0 Aug 8, 2021

#190 in Rust patterns

Download history 1/week @ 2022-01-27 2/week @ 2022-02-03 154/week @ 2022-02-10 31/week @ 2022-02-17 9/week @ 2022-02-24 29/week @ 2022-03-03 74/week @ 2022-03-10 40/week @ 2022-03-17 49/week @ 2022-03-24 38/week @ 2022-03-31 176/week @ 2022-04-07 70/week @ 2022-04-14 818/week @ 2022-04-21 787/week @ 2022-04-28 1938/week @ 2022-05-05 1826/week @ 2022-05-12

5,392 downloads per month
Used in 8 crates (5 directly)

MIT/Apache

55KB
858 lines

Crates.io API reference

Overview

async_once_cell is a version of once_cell that adds support for async initialization of cells. The short version of the API is:

impl OnceCell<T> {
    fn new() -> OnceCell<T>;
    fn get(&self) -> Option<&T>;
    async fn get_or_init(&self, init: impl Future<Output=T>) -> &T;
}

More patterns and use-cases are in the docs!

Related crates


lib.rs:

A collection of lazy initialized values that are created by Futures.

[OnceCell]'s API should be familiar to anyone who has used the once_cell crate or the proposed std::lazy module. It provides an async version of a cell that can only be initialized once, permitting tasks to wait on the initialization if it is already running instead of racing multiple initialization tasks.

Unlike threads, tasks can be cancelled at any point where they block. [OnceCell] deals with this by allowing another initializer to run if the task currently initializing the cell is dropped. This also allows for fallible initialization using [OnceCell::get_or_try_init], and for the initializing Future to contain borrows or use references to thread-local data.

[Lazy] takes the opposite approach: it wraps a single Future which is cooperatively run to completion by any polling task. This requires that the initialization function be independent of the calling context, but will never restart an initializing function just because the surrounding task was cancelled.

Overhead

Both cells use two usizes to store state and do not retain any allocations after initialization is complete. [OnceCell] and [Lazy] only allocate if there is contention.

No runtime deps

Features

  • unpin