【tokio】watch

watch

一个单一生产者、多消费者的通道,只保留最后发送的值。

示例

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

#[tokio::main]
async fn main() {
    let (tx, mut rx) = watch::channel("hello");
    let mut rx2 = rx.clone();
    
    tokio::spawn(async move {
        while rx.changed().await.is_ok() {
            println!("received1 = {:?}", *rx.borrow());
        }
    });

    tokio::spawn(async move {
        while rx2.changed().await.is_ok() {
            println!("received2 = {:?}", *rx2.borrow());
        }
    });
    
    tx.send("first").expect("send error!");
    tx.send("second").expect("send error!");
    
    sleep(Duration::from_millis(3000)).await;
}

输出

received1 = "second"
received2 = "second"

你可能感兴趣的:(tokio,javascript,前端,开发语言)