async_cell
The key type of this crate is 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 aCell<Option<T>>
that you can await on.
For example, it can be used to author futures in a callbacky style:
use AsyncCell;
let cell = shared;
let future = cell.take_shared;
spawn;
println!;
In place of something like tokio::sync::watch
to react to the latest value
of a variable:
use AsyncCell;
// Allocate space for our counter.
let counter_to_print = shared;
// Try to print out the counts as fast as we receive them.
let c = counter_to_print.clone;
spawn;
// Begin counting!
for i in 0..1000
counter_to_print.set;
To juggle a Waker
within more complex data structures:
use AsyncCell;
use RefCell;
// A simple channel for sending numbers.
Or can be used in place of a lazy_static + a oneshot channel to initialize some resource:
use AsyncCell;
// AsyncCell::new() is const!
static DATA: = new;
// Read the file on a background thread.
spawn;
// Do some work while waiting for the file.
// And ready!
assert_eq!;
What can't async_cell do?
- Be used to broadcast data. If you need multiple concurrent consumers, get yourself a channel.
- Guarantee that multiple sent values are received. When a cell is set in a loop, the receiver might wake up only once, long after, and take the last.
Although this crate contains a number of utility functions, you should generally
be able to make due with just AsyncCell::new
, AsyncCell::set
, and
AsyncCell::take
.