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

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

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

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

            
25
1
    // Wait for the thread to exit.
26
1
    watching_thread.join().unwrap();
27
1
}
28

            
29
1
fn watching_thread(watcher: Watcher<u32>) {
30
    // A Watcher can be used as an iterator which always reads the most
31
    // recent value, or parks the current thread until a new value is available.
32
7
    for value in watcher {
33
6
        // The value we read will not necessarily be sequential, even though the
34
6
        // main thread is storing a complete sequence.
35
6
        println!("Read value: {value}");
36
6
    }
37
1
}
38
// end rustme snippet: example
39

            
40
1
#[test]
41
1
fn runs() {
42
1
    main()
43
1
}