pub struct Observable<T> { /* private fields */ }Expand description
A shared, version-tracked value with change notification.
Cloning an Observable creates a new handle to the same inner state —
both handles see the same value and share subscribers.
§Invariants
versionincrements by exactly 1 on each value-changing mutation.set(v)wherev == currentis a no-op.- Subscribers are notified in registration order.
- Dead subscribers (dropped
Subscriptionguards) are pruned lazily.
Implementations§
Source§impl<T: Clone + PartialEq + 'static> Observable<T>
impl<T: Clone + PartialEq + 'static> Observable<T>
Sourcepub fn new(value: T) -> Self
pub fn new(value: T) -> Self
Create a new observable with the given initial value.
The initial version is 0 and no subscribers are registered.
Sourcepub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R
pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R
Access the current value by reference without cloning.
The closure f receives an immutable reference to the value.
Sourcepub fn set(&self, value: T)
pub fn set(&self, value: T)
Set a new value. If the new value differs from the current value
(by PartialEq), the version is incremented and all live subscribers
are notified.
This method is safe to call re-entrantly from within subscriber callbacks.
Sourcepub fn update(&self, f: impl FnOnce(&mut T))
pub fn update(&self, f: impl FnOnce(&mut T))
Modify the value in place via a closure. If the value changes
(compared by PartialEq against a snapshot), the version is
incremented and subscribers are notified.
This method is safe to call re-entrantly from within subscriber callbacks.
Sourcepub fn subscribe(&self, callback: impl Fn(&T) + 'static) -> Subscription
pub fn subscribe(&self, callback: impl Fn(&T) + 'static) -> Subscription
Subscribe to value changes. The callback is invoked with a reference to the new value each time it changes.
Returns a Subscription guard. Dropping the guard unsubscribes
the callback (it will not be called after drop, though it may still
be in the subscriber list until the next notify() prunes it).
Sourcepub fn version(&self) -> u64
pub fn version(&self) -> u64
Current version number. Increments by 1 on each value-changing mutation. Useful for dirty-checking in render loops.
Sourcepub fn subscriber_count(&self) -> usize
pub fn subscriber_count(&self) -> usize
Number of currently registered subscribers (including dead ones not yet pruned).