Struct async_broadcast::Sender

source ·
pub struct Sender<T> { /* private fields */ }
Expand description

The sending side of the broadcast channel.

Senders can be cloned and shared among threads. When all senders associated with a channel are dropped, the channel becomes closed.

The channel can also be closed manually by calling Sender::close().

Implementations§

Returns the channel capacity.

Examples
use async_broadcast::broadcast;

let (s, r) = broadcast::<i32>(5);
assert_eq!(s.capacity(), 5);

Set the channel capacity.

There are times when you need to change the channel’s capacity after creating it. If the new_cap is less than the number of messages in the channel, the oldest messages will be dropped to shrink the channel.

Examples
use async_broadcast::{broadcast, TrySendError, TryRecvError};

let (mut s, mut r) = broadcast::<i32>(3);
assert_eq!(s.capacity(), 3);
s.try_broadcast(1).unwrap();
s.try_broadcast(2).unwrap();
s.try_broadcast(3).unwrap();

s.set_capacity(1);
assert_eq!(s.capacity(), 1);
assert_eq!(r.try_recv(), Err(TryRecvError::Overflowed(2)));
assert_eq!(r.try_recv().unwrap(), 3);
assert_eq!(r.try_recv(), Err(TryRecvError::Empty));
s.try_broadcast(1).unwrap();
assert_eq!(s.try_broadcast(2), Err(TrySendError::Full(2)));

s.set_capacity(2);
assert_eq!(s.capacity(), 2);
s.try_broadcast(2).unwrap();
assert_eq!(s.try_broadcast(2), Err(TrySendError::Full(2)));

If overflow mode is enabled on this channel.

Examples
use async_broadcast::broadcast;

let (s, r) = broadcast::<i32>(5);
assert!(!s.overflow());

Set overflow mode on the channel.

When overflow mode is set, broadcasting to the channel will succeed even if the channel is full. It achieves that by removing the oldest message from the channel.

Examples
use async_broadcast::{broadcast, TrySendError, TryRecvError};

let (mut s, mut r) = broadcast::<i32>(2);
s.try_broadcast(1).unwrap();
s.try_broadcast(2).unwrap();
assert_eq!(s.try_broadcast(3), Err(TrySendError::Full(3)));
s.set_overflow(true);
assert_eq!(s.try_broadcast(3).unwrap(), Some(1));
assert_eq!(s.try_broadcast(4).unwrap(), Some(2));

assert_eq!(r.try_recv(), Err(TryRecvError::Overflowed(2)));
assert_eq!(r.try_recv().unwrap(), 3);
assert_eq!(r.try_recv().unwrap(), 4);
assert_eq!(r.try_recv(), Err(TryRecvError::Empty));

If sender will wait for active receivers.

If set to false, Send will resolve immediately with a SendError. Defaults to true.

Examples
use async_broadcast::broadcast;

let (s, _) = broadcast::<i32>(5);
assert!(s.await_active());

Specify if sender will wait for active receivers.

If set to false, Send will resolve immediately with a SendError. Defaults to true.

Examples
use async_broadcast::broadcast;

let (mut s, mut r) = broadcast::<i32>(2);
s.broadcast(1).await.unwrap();

let _ = r.deactivate();
s.set_await_active(false);
assert!(s.broadcast(2).await.is_err());

Closes the channel.

Returns true if this call has closed the channel and it was not closed already.

The remaining messages can still be received.

Examples
use async_broadcast::{broadcast, RecvError};

let (s, mut r) = broadcast(1);
s.broadcast(1).await.unwrap();
assert!(s.close());

assert_eq!(r.recv().await.unwrap(), 1);
assert_eq!(r.recv().await, Err(RecvError::Closed));

Returns true if the channel is closed.

Examples
use async_broadcast::{broadcast, RecvError};

let (s, r) = broadcast::<()>(1);
assert!(!s.is_closed());

drop(r);
assert!(s.is_closed());

Returns true if the channel is empty.

Examples
use async_broadcast::broadcast;

let (s, r) = broadcast(1);

assert!(s.is_empty());
s.broadcast(1).await;
assert!(!s.is_empty());

Returns true if the channel is full.

Examples
use async_broadcast::broadcast;

let (s, r) = broadcast(1);

assert!(!s.is_full());
s.broadcast(1).await;
assert!(s.is_full());

Returns the number of messages in the channel.

Examples
use async_broadcast::broadcast;

let (s, r) = broadcast(2);
assert_eq!(s.len(), 0);

s.broadcast(1).await;
s.broadcast(2).await;
assert_eq!(s.len(), 2);

Returns the number of receivers for the channel.

This does not include inactive receivers. Use Sender::inactive_receiver_count if you are interested in that.

Examples
use async_broadcast::broadcast;

let (s, r) = broadcast::<()>(1);
assert_eq!(s.receiver_count(), 1);
let r = r.deactivate();
assert_eq!(s.receiver_count(), 0);

let r2 = r.activate_cloned();
assert_eq!(r.receiver_count(), 1);
assert_eq!(r.inactive_receiver_count(), 1);

Returns the number of inactive receivers for the channel.

Examples
use async_broadcast::broadcast;

let (s, r) = broadcast::<()>(1);
assert_eq!(s.receiver_count(), 1);
let r = r.deactivate();
assert_eq!(s.receiver_count(), 0);

let r2 = r.activate_cloned();
assert_eq!(r.receiver_count(), 1);
assert_eq!(r.inactive_receiver_count(), 1);

Returns the number of senders for the channel.

Examples
use async_broadcast::broadcast;

let (s, r) = broadcast::<()>(1);
assert_eq!(s.sender_count(), 1);

let s2 = s.clone();
assert_eq!(s.sender_count(), 2);

Produce a new Receiver for this channel.

The new receiver starts with zero messages available. This will not re-open the channel if it was closed due to all receivers being dropped.

Examples
use async_broadcast::{broadcast, RecvError};

let (s, mut r1) = broadcast(2);

assert_eq!(s.broadcast(1).await, Ok(None));

let mut r2 = s.new_receiver();

assert_eq!(s.broadcast(2).await, Ok(None));
drop(s);

assert_eq!(r1.recv().await, Ok(1));
assert_eq!(r1.recv().await, Ok(2));
assert_eq!(r1.recv().await, Err(RecvError::Closed));

assert_eq!(r2.recv().await, Ok(2));
assert_eq!(r2.recv().await, Err(RecvError::Closed));

Broadcasts a message on the channel.

If the channel is full, this method waits until there is space for a message unless:

  1. overflow mode (set through Sender::set_overflow) is enabled, in which case it removes the oldest message from the channel to make room for the new message. The removed message is returned to the caller.
  2. this behavior is disabled using Sender::set_await_active, in which case, it returns SendError immediately.

If the channel is closed, this method returns an error.

Examples
use async_broadcast::{broadcast, SendError};

let (s, r) = broadcast(1);

assert_eq!(s.broadcast(1).await, Ok(None));
drop(r);
assert_eq!(s.broadcast(2).await, Err(SendError(2)));

Attempts to broadcast a message on the channel.

If the channel is full, this method returns an error unless overflow mode (set through Sender::set_overflow) is enabled. If the overflow mode is enabled, it removes the oldest message from the channel to make room for the new message. The removed message is returned to the caller.

If the channel is closed, this method returns an error.

Examples
use async_broadcast::{broadcast, TrySendError};

let (s, r) = broadcast(1);

assert_eq!(s.try_broadcast(1), Ok(None));
assert_eq!(s.try_broadcast(2), Err(TrySendError::Full(2)));

drop(r);
assert_eq!(s.try_broadcast(3), Err(TrySendError::Closed(3)));
Examples found in repository?
src/lib.rs (line 1547)
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut this = Pin::new(self);

        loop {
            let msg = this.msg.take().unwrap();
            let inner = &this.sender.inner;

            // Attempt to send a message.
            match this.sender.try_broadcast(msg) {
                Ok(msg) => {
                    let inner = inner.write();

                    if inner.queue.len() < inner.capacity {
                        // Not full still, so notify the next awaiting sender.
                        inner.send_ops.notify(1);
                    }

                    return Poll::Ready(Ok(msg));
                }
                Err(TrySendError::Closed(msg)) => return Poll::Ready(Err(SendError(msg))),
                Err(TrySendError::Full(m)) => this.msg = Some(m),
                Err(TrySendError::Inactive(m)) if inner.read().await_active => this.msg = Some(m),
                Err(TrySendError::Inactive(m)) => return Poll::Ready(Err(SendError(m))),
            }

            // Sending failed - now start listening for notifications or wait for one.
            match &mut this.listener {
                None => {
                    // Start listening and then try sending again.
                    let inner = inner.write();
                    this.listener = Some(inner.send_ops.listen());
                }
                Some(l) => {
                    // Wait for a notification.
                    ready!(Pin::new(l).poll(cx));
                    this.listener = None;
                }
            }
        }
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.