Use tokio::sync::watch::channel to create a sender and receiver pair for broadcasting the latest value to multiple listeners.
use tokio::sync::watch;
#[tokio::main]
async fn main() {
let (tx, mut rx) = watch::channel(0);
// Spawn a task to receive updates
tokio::spawn(async move {
while rx.changed().await.is_ok() {
println!("New value: {}", *rx.borrow());
}
});
// Send updates
tx.send(1).unwrap();
tx.send(2).unwrap();
}
- Import the
watchmodule fromtokio::sync. - Create a channel with an initial value using
watch::channel(initial_value). - Await
rx.changed()to block until a new value arrives. - Read the current value using
*rx.borrow(). - Send new values using
tx.send(value).
The receiver automatically drops old values and only holds the latest one, making it ideal for configuration updates or state broadcasting.