7 unstable releases
0.4.2 | Jun 27, 2022 |
---|---|
0.4.1 | Jun 27, 2022 |
0.4.0 | May 14, 2022 |
0.3.1 | May 11, 2022 |
0.1.0 | Aug 8, 2021 |
#109 in Rust patterns
19,569 downloads per month
Used in 34 crates
(11 directly)
56KB
858 lines
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 Future
s.
[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 usize
s 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