pub struct AsyncOnceCell<T> { /* private fields */ }Expand description
An asynchronous once cell: the first future returned by
get_or_init to be polled runs its
initializer to completion and caches the output; every other poll of any
future created for the cell waits for that value and resolves to a shared
reference to it.
Unlike std::sync::OnceLock, initialization happens inside the polling
task: the initializer future is polled in the context of the first caller,
so no thread blocks, no task is spawned and no runtime is required.
§Cancellation and panics
If the initializing future is dropped before it finishes (the awaiting task
was cancelled) or its poll panics, the cell rolls back to empty and the
next call runs the initializer again, so a body passed to get_or_init may
run more than once. This matches the retry semantics of
std::sync::OnceLock.
§Reentrancy
A future that re-enters the same cell’s get_or_init while that cell is
initializing would wait for itself; such a call panics with a clear message
instead of deadlocking. Initializing a different cell from inside an
initializer is supported.
§Examples
use once_fn::AsyncOnceCell;
static CELL: AsyncOnceCell<u32> = AsyncOnceCell::new();
#[tokio::main]
async fn main() {
let a = CELL.get_or_init(|| async { 7 }).await;
let b = CELL.get_or_init(|| async { unreachable!() }).await;
assert_eq!((a, b), (&7, &7));
}Implementations§
Source§impl<T> AsyncOnceCell<T>
impl<T> AsyncOnceCell<T>
Sourcepub fn get_or_init<F, Fut>(&self, f: F) -> GetOrInit<'_, T, F, Fut>
pub fn get_or_init<F, Fut>(&self, f: F) -> GetOrInit<'_, T, F, Fut>
Return a future that resolves to a reference to the cached value,
initializing the cell with f if needed.
The first future to be polled calls f and polls the returned future
in the caller’s task context; futures polled while initialization is in
flight park as waiters and are woken once the value is stored.
§Panics
Panics if the cell is re-entered from inside its own initializer, which would otherwise deadlock waiting for itself.