<div align="center">
<h1>async-observe</h1>
<p>
Async single-producer, multi-consumer channel that only retains the last sent value
</p>
<p>
<a href="https://crates.io/crates/async"><img src="https://img.shields.io/crates/v/async.svg"></img></a>
<a href="https://docs.rs/async"><img src="https://docs.rs/async/badge.svg"></img></a>
</p>
</div>
## 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.
[`channel`]: https://docs.rs/async-observe/latest/async-observe/fn.channel.html
[`Sender`]: https://docs.rs/async-observe/latest/async-observe/struct.Sender.html
[`Receiver`]: https://docs.rs/async-observe/latest/async-observe/struct.Receiver.html
[`observe`]: https://docs.rs/async-observe/latest/async-observe/struct.Receiver.html#method.observe
[`changed`]: https://docs.rs/async-observe/latest/async-observe/struct.Receiver.html#method.changed
[`recv`]: https://docs.rs/async-observe/latest/async-observe/struct.Receiver.html#method.recv
[`send`]: https://docs.rs/async-observe/latest/async-observe/struct.Sender.html#method.send
## Examples
This example prints numbers from 0 to 9:
```rust
use {
futures_lite::future,
std::{thread, time::Duration},
};
let (tx, mut rx) = async_observe::channel(0);
// Perform computations in another thread
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)
// 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`].
[`async-channel`]: https://docs.rs/async-channel/latest/async_channel