pub struct Sender<T> { /* private fields */ }
Implementations§
Source§impl<T> Sender<T>
impl<T> Sender<T>
Sourcepub fn send(&self, value: T) -> Result<(), SendError<T>>
pub fn send(&self, value: T) -> Result<(), SendError<T>>
Sends a new value to the channel and notifies all receivers.
§Examples
let (tx, rx) = async_observe::channel(0);
assert_eq!(rx.observe(|n| *n), 0);
// Send a new value
tx.send(1);
// Now the receiver can see it
assert_eq!(rx.observe(|n| *n), 1);
To wait until the value is updated, use the receiver’s async methods
changed
or recv
.
Sourcepub async fn closed(&self)
pub async fn closed(&self)
Waits until all receivers are dropped.
§Examples
A producer can wait until no consumers is interested in its updates anymore and then stop working.
use futures_lite::future;
let (tx, mut rx) = async_observe::channel(0);
// The producer runs concurrently and waits until the channel
// is closed, then cancels the main future
let producer = future::or(
async {
let mut n = 0;
loop {
wait_long_time().await;
// The producer could check if the channel is closed on send,
// but computing a new value might take a long time.
// Instead, we cancel the whole working future.
_ = tx.send(n);
n += 1;
}
},
tx.closed(),
);
let consumer = async move {
// ^^^^
// Note: rx is moved into this future,
// so it will be dropped when the loop ends.
// Alternatively, you could call `drop(rx);` explicitly.
while let Ok(n) = rx.recv().await {
// After receiving number 5,
// the consumer is no longer interested.
if n == 5 {
break;
}
}
};
future::zip(producer, consumer).await;
The receiver is dropped after getting the number 5. Since there are no
other receivers, this makes tx.closed()
finish and the sender stops
sending new values.
Trait Implementations§
Auto Trait Implementations§
impl<T> Freeze for Sender<T>
impl<T> RefUnwindSafe for Sender<T>
impl<T> Send for Sender<T>
impl<T> Sync for Sender<T>
impl<T> Unpin for Sender<T>
impl<T> UnwindSafe for Sender<T>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more