pub fn channel<T>(init: T) -> (Sender<T>, Receiver<T>)
Expand description
Creates a new observer channel, returning the sender and receiver halves.
All values sent by Sender
will become visible to the Receiver
handles. Only the last value sent is made available to the Receiver
half. All intermediate values are dropped.
ยง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
.