Expand description
§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
.
Structs§
- Receiver
- Receives values from the associated
Sender
. - Recv
Error - Error produced when receiving a change notification.
- Send
Error - Error produced when sending a value fails.
- Sender
- Sends values to the associated
Receiver
s.
Functions§
- channel
- Creates a new observer channel, returning the sender and receiver halves.