Skip to content

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

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT
Notifications You must be signed in to change notification settings

nanoqsh/async-observe

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

async-observe

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

Usage

The channel function creates a pair of Sender and Receiver. To create the channel provide its initial value.

Each receiver independently tracks the last observed value. To read the current value, use the receiver's observe method. To wait for a change, call the async changed method on the receiver. If the value implements Clone, you can also use the recv method to wait for a change and immediately read the new value.

To update the value, call the sender's send method. This method is non-async and does not block the current thread - the value is updated immediately. This makes it convenient to send values from both async and synchronous contexts.

Examples

This example prints numbers from 0 to 9:

use {
    futures_lite::future,
    std::{thread, time::Duration},
};

let (tx, mut rx) = async_observe::channel(0);

// Perform computations in another thread
thread::spawn(move || {
    for n in 1..10 {
        thread::sleep(Duration::from_secs(1));

        // Send a new value without blocking the thread.
        // If sending fails, it means the sender was dropped.
        // In that case stop the computation.
        if tx.send(n).is_err() {
            break;
        }
    }
});

// Print the initial value (0)
let n = rx.observe(|n| *n);
println!("{n}");

future::block_on(async {
    // Print the value whenever it changes
    while let Ok(n) = rx.recv().await {
        println!("{n}");
    }
});

In this example a new thread is spawned, but you can also use the channel to update values from a future/async task.

Note that this channel does not have a message queue - it only stores the latest update. Therefore, it does not guarantee that you will observe every intermediate value. If you need to observe each change, use a message-queue channel such as async-channel.

About

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

Resources

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT

Stars

Watchers

Forks

Releases

No releases published

Languages