pub struct Watchable<T> { /* private fields */ }Expand description
A wrapper around a value that notifies Watchers when the value is modified.
Only the most recent value is available to any observer, but the observer is guaranteed to be notified of the most recent value.
Implementations§
Source§impl<T: Clone + Eq> Watchable<T>
impl<T: Clone + Eq> Watchable<T>
Sourcepub fn set(&self, value: T) -> Result<T, T>
pub fn set(&self, value: T) -> Result<T, T>
Sets a new value.
Returns Ok(previous_value) if the value was different from the one set, or
returns the provided value back as Err(value) if the value didn’t change.
Watchers are only notified if the value changed.
Sourcepub fn modify<F, R>(&self, f: F) -> R
pub fn modify<F, R>(&self, f: F) -> R
Atomically modifies the value using a closure.
The closure receives a mutable reference to the current value and may modify
it in place. The read-modify-write is performed under a write lock, so it
happens atomically with respect to other callers of Watchable::set,
Watchable::modify, Watchable::get, and Watchers. The closure
should therefore be fast and must not call back into this Watchable
(doing so will deadlock).
Watchers are only notified if the value actually changed, as determined by
Eq. Whatever the closure returns is forwarded as the return value of this
method, which makes it convenient for expressing compare-and-swap:
let watchable = Watchable::new(42);
let swapped = watchable.modify(|value| {
if *value == 42 {
*value = 100;
true
} else {
false
}
});
assert!(swapped);
assert_eq!(watchable.get(), 100);Sourcepub fn has_watchers(&self) -> bool
pub fn has_watchers(&self) -> bool
Returns true when there are any watchers actively listening on changes, or false when all watchers have been dropped or none have been created yet.