Module pawawwewism::reactive

source ·
Expand description

Primitives for reactive programming.

Value encapsulates some value and adds the ability to listen for changes of that value. It supports both blocking and async listeners.

Analogues

A Value and its associated Readers are comparable to a broadcast channel, since any change to the Value will notify every Reader. However, there is an important difference: changes to the Value are generally coalesced, meaning that Readers are not guaranteed to see intermediate values if the value is changed again before the Reader has time to witness the old value.

A closer analogue to Value and Reader would be tokio’s sync::watch module and its Sender and Receiver. The difference is that this implementation supports both async and sync usage and is completely independent of any async runtime.

Examples

use pawawwewism::reactive::Value;

let mut value = Value::new(0);
let reader = value.reader();

// A background thread performs calculations and publishes the results.
let bg = pawawwewism::background(move || for i in 1..=10 {
    value.set(i);
});

// `Reader` can be iterated over, yielding changes to the value. Unlike a channel, `Reader` is
// not guaranteed to yield *every* value, only the most recent one.
let mut last = 0;
for value in reader {
    last = value;
}
assert_eq!(last, 10);

Structs