Enables watching for value changes in both multi-threaded and asynchronous contexts. Similar to tokio::sync::watch, but able to work in non-async codebases.
watchable
is a Multi-Producer, Multi-Consumer channel where each consumer
is only guaranteed to receive the most recently written value.
```rust use watchable::{Watchable, Watcher};
fn main() {
// Create a Watchable
// 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 thread to exit.
watching_thread.join().unwrap();
}
fn watching_thread(watcher: Watcher
When running this example, the output will look similar to:
sh
...
Read value: 876
Read value: 897
Read value: 923
Read value: 944
Read value: 957
Read value: 977
Read value: 995
Read value: 1000
As you can see, the receiving thread doesn't receive every value. Each watcher is guaranteed to be notified when changes occur and is guaranteed to be able to retrieve the most recent value.
The Watcher
type can be used in async code in multiple ways:
Watcher::into_stream()
: Wraps the watcher in a type that implements
futures::Stream
.Watcher::wait_async().await
: Pauses execution of the current task until a
new value is available to be read. Watcher::read()
can be used to retrieve
the current value after wait_async()
has returned.Here is the same example as above, except this time using Watcher::into_stream
with Tokio:
```rust use futures_util::StreamExt; use watchable::{Watchable, Watcher};
async fn main() {
// Create a Watchable
// 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 watchingtask(watcher: Watcher
watchable
is compatible with all async runtimes.
This project, like all projects from Khonsu Labs, are open-source. This repository is available under the MIT License or the Apache License 2.0.
To learn more about contributing, please see CONTRIBUTING.md.