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

Sending-half of the broadcast channel.

May be used from many threads. Messages can be sent with send.

Examples

use tokio::sync::broadcast;

#[tokio::main]
async fn main() {
    let (tx, mut rx1) = broadcast::channel(16);
    let mut rx2 = tx.subscribe();

    tokio::spawn(async move {
        assert_eq!(rx1.recv().await.unwrap(), 10);
        assert_eq!(rx1.recv().await.unwrap(), 20);
    });

    tokio::spawn(async move {
        assert_eq!(rx2.recv().await.unwrap(), 10);
        assert_eq!(rx2.recv().await.unwrap(), 20);
    });

    tx.send(10).unwrap();
    tx.send(20).unwrap();
}

Implementations§

source§

impl<T> Sender<T>

source

pub fn send(&self, value: T) -> Result<usize, SendError<T>>

Attempts to send a value to all active Receiver handles, returning it back if it could not be sent.

A successful send occurs when there is at least one active Receiver handle. An unsuccessful send would be one where all associated Receiver handles have already been dropped.

Return

On success, the number of subscribed Receiver handles is returned. This does not mean that this number of receivers will see the message as a receiver may drop before receiving the message.

Note

A return value of Ok does not mean that the sent value will be observed by all or any of the active Receiver handles. Receiver handles may be dropped before receiving the sent message.

A return value of Err does not mean that future calls to send will fail. New Receiver handles may be created by calling subscribe.

Examples
use tokio::sync::broadcast;

#[tokio::main]
async fn main() {
    let (tx, mut rx1) = broadcast::channel(16);
    let mut rx2 = tx.subscribe();

    tokio::spawn(async move {
        assert_eq!(rx1.recv().await.unwrap(), 10);
        assert_eq!(rx1.recv().await.unwrap(), 20);
    });

    tokio::spawn(async move {
        assert_eq!(rx2.recv().await.unwrap(), 10);
        assert_eq!(rx2.recv().await.unwrap(), 20);
    });

    tx.send(10).unwrap();
    tx.send(20).unwrap();
}
source

pub fn subscribe(&self) -> Receiver<T>

Creates a new Receiver handle that will receive values sent after this call to subscribe.

Examples
use tokio::sync::broadcast;

#[tokio::main]
async fn main() {
    let (tx, _rx) = broadcast::channel(16);

    // Will not be seen
    tx.send(10).unwrap();

    let mut rx = tx.subscribe();

    tx.send(20).unwrap();

    let value = rx.recv().await.unwrap();
    assert_eq!(20, value);
}
source

pub fn len(&self) -> usize

Returns the number of queued values.

A value is queued until it has either been seen by all receivers that were alive at the time it was sent, or has been evicted from the queue by subsequent sends that exceeded the queue’s capacity.

Note

In contrast to Receiver::len, this method only reports queued values and not values that have been evicted from the queue before being seen by all receivers.

Examples
use tokio::sync::broadcast;

#[tokio::main]
async fn main() {
    let (tx, mut rx1) = broadcast::channel(16);
    let mut rx2 = tx.subscribe();

    tx.send(10).unwrap();
    tx.send(20).unwrap();
    tx.send(30).unwrap();

    assert_eq!(tx.len(), 3);

    rx1.recv().await.unwrap();

    // The len is still 3 since rx2 hasn't seen the first value yet.
    assert_eq!(tx.len(), 3);

    rx2.recv().await.unwrap();

    assert_eq!(tx.len(), 2);
}
source

pub fn is_empty(&self) -> bool

Returns true if there are no queued values.

Examples
use tokio::sync::broadcast;

#[tokio::main]
async fn main() {
    let (tx, mut rx1) = broadcast::channel(16);
    let mut rx2 = tx.subscribe();

    assert!(tx.is_empty());

    tx.send(10).unwrap();

    assert!(!tx.is_empty());

    rx1.recv().await.unwrap();

    // The queue is still not empty since rx2 hasn't seen the value.
    assert!(!tx.is_empty());

    rx2.recv().await.unwrap();

    assert!(tx.is_empty());
}
source

pub fn receiver_count(&self) -> usize

Returns the number of active receivers

An active receiver is a Receiver handle returned from channel or subscribe. These are the handles that will receive values sent on this Sender.

Note

It is not guaranteed that a sent message will reach this number of receivers. Active receivers may never call recv again before dropping.

Examples
use tokio::sync::broadcast;

#[tokio::main]
async fn main() {
    let (tx, _rx1) = broadcast::channel(16);

    assert_eq!(1, tx.receiver_count());

    let mut _rx2 = tx.subscribe();

    assert_eq!(2, tx.receiver_count());

    tx.send(10).unwrap();
}
source

pub fn same_channel(&self, other: &Sender<T>) -> bool

Returns true if senders belong to the same channel.

Examples
use tokio::sync::broadcast;

#[tokio::main]
async fn main() {
    let (tx, _rx) = broadcast::channel::<()>(16);
    let tx2 = tx.clone();

    assert!(tx.same_channel(&tx2));

    let (tx3, _rx3) = broadcast::channel::<()>(16);

    assert!(!tx3.same_channel(&tx2));
}

Trait Implementations§

source§

impl<T> Clone for Sender<T>

source§

fn clone(&self) -> Sender<T>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T> Debug for Sender<T>

source§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl<T> Drop for Sender<T>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<T> Send for Sender<T>where T: Send,

source§

impl<T> Sync for Sender<T>where T: Send,

Auto Trait Implementations§

§

impl<T> !RefUnwindSafe for Sender<T>

§

impl<T> Unpin for Sender<T>

§

impl<T> !UnwindSafe for Sender<T>

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Any for Twhere T: Any,

§

fn into_any(self: Box<T, Global>) -> Box<dyn Any, Global>

§

fn into_any_rc(self: Rc<T, Global>) -> Rc<dyn Any, Global>

§

fn type_name(&self) -> &'static str

§

impl<T> AnySync for Twhere T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T, Global>) -> Arc<dyn Any + Sync + Send, Global>

§

impl<T> ArchivePointee for T

§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<F, W, T, D> Deserialize<With<T, W>, D> for Fwhere W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized,

§

fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::Error>

Deserializes using the given deserializer
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FutureExt for T

§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

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

§

impl<T> Pointable for T

§

const ALIGN: usize = mem::align_of::<T>()

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> Pointee for T

§

type Metadata = ()

The type for metadata in pointers and references to Self.
source§

impl<T> Same<T> for T

§

type Output = T

Should always be Self
§

impl<SS, SP> SupersetOf<SS> for SPwhere SS: SubsetOf<SP>,

§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> Upcastable for Twhere T: Any + Send + Sync + 'static,

§

fn upcast_any_ref(&self) -> &(dyn Any + 'static)

upcast ref
§

fn upcast_any_mut(&mut self) -> &mut (dyn Any + 'static)

upcast mut ref
§

fn upcast_any_box(self: Box<T, Global>) -> Box<dyn Any, Global>

upcast boxed dyn
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
§

impl<T> State for Twhere T: Debug + Clone + Send + Sync,