1
// begin rustme snippet: example
2
use futures_util::StreamExt;
3
use watchable::{Watchable, Watcher};
4

            
5
#[tokio::main]
6
1
async fn main() {
7
1
    // Create a Watchable<u32> which holds a u32 and notifies watchers when the
8
1
    // contained value changes.
9
1
    let watchable = Watchable::default();
10
1
    // Create a watcher that will efficiently be able to monitor and read the
11
1
    // contained value as it is updated.
12
1
    let watcher = watchable.watch();
13
1
    // Spawn a background worker that will print out the values the watcher reads.
14
1
    let watching_task = tokio::task::spawn(watching_task(watcher));
15

            
16
    // Store a sequence of values. Each time a new value is written, any waiting
17
    // watchers will be notified there is a new value available.
18
1001
    for i in 1_u32..=1000 {
19
1000
        watchable.replace(i);
20
1000
    }
21

            
22
    // Once we're done sending values, dropping the Watchable will ensure
23
    // watchers are notified of the disconnection. Watchers are guaranteed to be
24
    // able to read the final value.
25
1
    drop(watchable);
26
1

            
27
1
    // Wait for the spawned task to exit.
28
1
    watching_task.await.unwrap();
29
}
30

            
31
1
async fn watching_task(watcher: Watcher<u32>) {
32
1
    // A Watcher can be converted into a Stream, which allows for asynchronous
33
1
    // iteration.
34
1
    let mut stream = watcher.into_stream();
35
5
    while let Some(value) = stream.next().await {
36
4
        // The value we received will not necessarily be sequential, even though
37
4
        // the main thread is publishing a complete sequence.
38
4
        println!("Read value: {value}");
39
4
    }
40
1
}
41
// end rustme snippet: example
42

            
43
1
#[test]
44
1
fn runs() {
45
1
    main()
46
1
}