[−][src]Module tokio::sync::watch
sync
only.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. The latest value stored in the channel is accessed with
Receiver::borrow()
. Awaiting Receiver::changed()
waits for a new
value to sent by the Sender
half.
Examples
use tokio::sync::watch; let (tx, mut rx) = watch::channel("hello"); tokio::spawn(async move { while rx.changed().await.is_ok() { println!("received = {:?}", *rx.borrow()); } }); tx.send("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 | sync Watch error types |
Structs
Receiver | sync Receives values from the associated |
Ref | sync Returns a reference to the inner value |
Sender | sync Sends values to the associated |
Functions
channel | sync Creates a new watch channel, returning the "send" and "receive" handles. |