How to use tokio watch channel

Use tokio::sync::watch::channel to broadcast the latest value to multiple async receivers efficiently.

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();
}
  1. Import the watch module from tokio::sync.
  2. Create a channel with an initial value using watch::channel(initial_value).
  3. Await rx.changed() to block until a new value arrives.
  4. Read the current value using *rx.borrow().
  5. 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.