Module tokio::sync::watch[][src]

A single-producer, multi-consumer channel that only retains the last sent value.

This channel is useful for watching for changes to a value from multiple points in the code base, for example, changes to configuration values.

Usage

channel returns a Sender / Receiver pair. These are the producer and sender halves of the channel. The channel is created with an initial value. Receiver::recv will always be ready upon creation and will yield either this initial value or the latest value that has been sent by Sender.

Calls to Receiver::recv will always yield the latest value.

Examples

use tokio::sync::watch;

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

    tokio::spawn(async move {
        while let Some(value) = rx.recv().await {
            println!("received = {:?}", value);
        }
    });

    tx.broadcast("world")?;

Closing

Sender::closed allows the producer to detect when all Receiver handles have been dropped. This indicates that there is no further interest in the values being produced and work can be stopped.

Thread safety

Both Sender and Receiver are thread safe. They can be moved to other threads and can be used in a concurrent environment. Clones of Receiver handles may be moved to separate threads and also used concurrently.

Modules

error

Watch error types

Structs

Receiver

Receives values from the associated Sender.

Ref

Returns a reference to the inner value

Sender

Sends values to the associated Receiver.

Functions

channel

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