Lines
100 %
Functions
Branches
// begin rustme snippet: example
use futures_util::StreamExt;
use watchable::{Watchable, Watcher};
#[tokio::main]
async fn main() {
// Create a Watchable<u32> which holds a u32 and notifies watchers when the
// contained value changes.
let watchable = Watchable::default();
// Create a watcher that will efficiently be able to monitor and read the
// contained value as it is updated.
let watcher = watchable.watch();
// Spawn a background worker that will print out the values the watcher reads.
let watching_task = tokio::task::spawn(watching_task(watcher));
// Store a sequence of values. Each time a new value is written, any waiting
// watchers will be notified there is a new value available.
for i in 1_u32..=1000 {
watchable.replace(i);
}
// Once we're done sending values, dropping the Watchable will ensure
// watchers are notified of the disconnection. Watchers are guaranteed to be
// able to read the final value.
drop(watchable);
// Wait for the spawned task to exit.
watching_task.await.unwrap();
async fn watching_task(watcher: Watcher<u32>) {
// A Watcher can be converted into a Stream, which allows for asynchronous
// iteration.
let mut stream = watcher.into_stream();
while let Some(value) = stream.next().await {
// The value we received will not necessarily be sequential, even though
// the main thread is publishing a complete sequence.
println!("Read value: {value}");
// end rustme snippet: example
#[test]
fn runs() {
main()