pub struct StateCell<T: Clone + Send + Sync + 'static> { /* private fields */ }Expand description
Holds the current value of T behind an Arc<RwLock>, plus a
tokio::sync::watch channel that fires every time the value
changes. Cheap to clone — the inner state + sender are
Arc-shared.
Implementations§
Source§impl<T: Clone + Send + Sync + 'static> StateCell<T>
impl<T: Clone + Send + Sync + 'static> StateCell<T>
Sourcepub fn new(initial: T) -> Self
pub fn new(initial: T) -> Self
Wrap an initial value. The initial value is also the watch
channel’s first observed snapshot — new subscribers see it
via borrow_and_update.
Sourcepub fn changes(&self) -> Receiver<T>
pub fn changes(&self) -> Receiver<T>
Subscribe to value changes. Receivers’ initial value is the
state at subscribe time — call borrow_and_update to read
without registering a “changed” notification.
Sourcepub async fn apply<F, E>(&self, f: F) -> Result<(), E>
pub async fn apply<F, E>(&self, f: F) -> Result<(), E>
Atomically transform the state. The closure receives ownership
of the previous value and returns Result<T, E>; on Ok the
new value is stored and broadcast; on Err the previous value
is preserved and the error is returned.
Holds the write lock for the duration of f — keep folds
CPU-bound. Long async work belongs outside the lock.
Sourcepub async fn set(&self, value: T)
pub async fn set(&self, value: T)
Replace the value unconditionally. Useful for resets / rewinds that don’t fit the fold pattern.
Sourcepub fn receiver_count(&self) -> usize
pub fn receiver_count(&self) -> usize
Live receiver count. Cheap; useful for skipping work when no one is listening.