| Crates.io | statewatcher |
| lib.rs | statewatcher |
| version | 0.1.0 |
| created_at | 2025-11-04 20:59:51.194139+00 |
| updated_at | 2025-11-04 20:59:51.194139+00 |
| description | A simple, shared state channel where readers are notified of updates, inspired by tokio::watch but for std |
| homepage | https://github.com/skandrk/state_watcher |
| repository | https://github.com/skandrk/state_watcher |
| max_upload_size | |
| id | 1916949 |
| size | 22,285 |
dry run publish
A simple, shared state channel where readers are notified of updates, inspired by tokio::watch but for std.
std implementationArc and RwLock/MutexMutex instead of RwLock for read-write accessA simple way to share state between threads with change notifications but without need to pull in Tokio or other async runtimes.
std::threadAdd this to your Cargo.toml:
[dependencies]
statewatcher = "0.1.0"
use statewatcher::state_channel;
fn main() {
let (writer, reader) = state_channel::<String>();
// Spawn a thread to watch for updates
std::thread::spawn(move || {
loop {
if let Some(value) = reader.latest_and_clear() {
println!("Received: {}", value);
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
});
// Update the state from another thread
writer.update("Hello, world!".to_string());
std::thread::sleep(std::time::Duration::from_secs(1));
}
use statewatcher::state_channel;
let (writer, reader1) = state_channel::<i32>();
let reader2 = reader1.clone();
let reader3 = reader1.clone();
writer.update(42);
// All readers see the update
assert_eq!(reader1.latest(), Some(42));
assert_eq!(reader2.latest(), Some(42));
assert_eq!(reader3.latest(), Some(42));
use statewatcher::state_channel;
let (writer, reader) = state_channel::<Vec<i32>>();
writer.update(vec![1, 2, 3, 4, 5]);
// Access state without cloning
let sum = reader.with_state(|vec| vec.iter().sum::<i32>());
println!("Sum: {}", sum);
Enable the mutex feature for a single handle that can both read and write:
[dependencies]
statewatcher = { version = "0.1.0", features = ["mutex"] }
use statewatcher::state_readerwriter;
fn main() {
let state = state_readerwriter::<i32>();
// Clone the handle for another thread
let state_clone = state.clone();
std::thread::spawn(move || {
state_clone.update(42);
});
std::thread::sleep(std::time::Duration::from_millis(100));
if let Some(value) = state.latest() {
println!("Value: {}", value);
}
}