async-watch

Async watch channel

2 releases

0.3.1 Oct 7, 2020
0.3.0 Sep 12, 2020
0.2.0 Aug 30, 2020
0.1.0 May 31, 2020

#2064 in Asynchronous

Download history 1948/week @ 2024-07-23 2520/week @ 2024-07-30 1781/week @ 2024-08-06 1570/week @ 2024-08-13 1959/week @ 2024-08-20 2036/week @ 2024-08-27 1644/week @ 2024-09-03 1583/week @ 2024-09-10 1661/week @ 2024-09-17 1578/week @ 2024-09-24 1541/week @ 2024-10-01 1544/week @ 2024-10-08 1376/week @ 2024-10-15 1400/week @ 2024-10-22 1601/week @ 2024-10-29 1270/week @ 2024-11-05

5,870 downloads per month
Used in ic-agent

Apache-2.0 OR MIT

16KB
157 lines

async-watch

Build License Cargo Documentation

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

Extracted from Tokio's tokio::sync::watch implementation, which was written by Carl Lerche.

License

async-watch is primarily distributed under the terms of both the MIT license and the Apache License (Version 2.0).

See LICENSE-APACHE and LICENSE-MIT for details.


lib.rs:

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

Extracted from Tokio's tokio::sync::watch implementation, which was written by Carl Lerche.

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. Awaiting [Receiver::recv()] combines [Receiver::changed()] and [Receiver::borrow()] where the borrowed value is cloned and returned.

Examples

let (tx, mut rx) = async_watch::channel("hello");
let mut rx2 = rx.clone();

// First variant
executor.spawn(async move {
    while let Ok(value) = rx.recv().await {
        println!("received = {:?}", value);
    }
});

// Second variant
executor.spawn(async move {
    while rx2.changed().await.is_ok() {
        println!("received = {:?}", *rx2.borrow());
    }
});

tx.send("world").unwrap();

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.

Dependencies

~135KB