tokio::sync::watch

Function channel

Source
pub fn channel<T>(init: T) -> (Sender<T>, Receiver<T>)
Expand description

Creates a new watch channel, returning the “send” and “receive” handles.

All values sent by Sender will become visible to the Receiver handles. Only the last value sent is made available to the Receiver half. All intermediate values are dropped.

§Examples

The following example prints hello! world! .

use tokio::sync::watch;
use tokio::time::{Duration, sleep};

let (tx, mut rx) = watch::channel("hello");

tokio::spawn(async move {
    // Use the equivalent of a "do-while" loop so the initial value is
    // processed before awaiting the `changed()` future.
    loop {
        println!("{}! ", *rx.borrow_and_update());
        if rx.changed().await.is_err() {
            break;
        }
    }
});

sleep(Duration::from_millis(100)).await;
tx.send("world")?;