# async_cell
[](https://gitlab.com/samsartor/async_cell/commits/master)
[](https://crates.io/crates/async_cell)
[](https://docs.rs/async_cell)
---
The key type of this crate is [`AsyncCell`](sync::AsyncCell) which can be
found in both thread-safe and single-threaded variants. It is intended as a
useful async primitive which can replace more expensive channels in a fair
number of cases.
> `AsyncCell<T>` behaves a lot like a `Cell<Option<T>>` that you can await
on.
This is used to create futures from a callbacks:
```rust
use async_cell::sync::AsyncCell;
let cell = AsyncCell::shared();
let future = cell.take_shared();
println!("{}", future.await);
```
You can also use an async_cell for static variable initilization, wherever
the blocking behavior of a `OnceCell` is unacceptable:
```rust
use async_cell::sync::AsyncCell;
// AsyncCell::new() is const!
static GREETING: AsyncCell<String> = AsyncCell::new();
// Read the file on a background thread.
GREETING.set(hello);
});
// Do some work while waiting for the file.
// And greet the user!
println!("{}", &GREETING.get().await);
```
Async cells can also be used to react to the latest value of a variable,
since the same cell can be reused as many times as desired. This is one
way `AsyncCell` differs from a one-shot channel:
```rust
use async_cell::sync::AsyncCell;
// Allocate space for our timer.
let timer = AsyncCell::<i32>::shared();
// Try to print out the time as fast as it updates.
let watcher = timer.take_weak();
spawn(async move {
while let Some(time) = (&watcher).await {
println!("Launch in T-{} seconds!", time);
}
});
// Begin counting down!
for i in (0..60).rev() {
timer.set(i);
}
```
Although this crate contains a number of utility functions, you can often
make due with just [`AsyncCell::new`](sync::AsyncCell::new),
[`AsyncCell::set`](sync::AsyncCell::set), and
[`AsyncCell::take`](sync::AsyncCell::take).
### Limitations
Do not use `AsyncCell` in situations with high contention! As a rule of thumb,
try to fill cells from one thread or task and empty from one other. _Although multiple
futures can wait on the same cell, that case is not highly optimized._
Also do not confuse an `AsyncCell` with full-blown channel. Channels deliver all
written value to readers; readers of an cell will only see the most recently written
value.