Skip to main content

Module oneshot

Module oneshot 

Source
Available on crate feature oneshot only.
Expand description

A one-shot channel is used for sending a single message between asynchronous tasks. The channel function is used to create a Sender and Receiver pair that form the channel.

The sender is used by the producer to send the value. The receiver is used by the consumer to receive the value.

The sender and receiver can be used by separate tasks.

Since Sender::send is not async, it can be used anywhere. This includes sending between two runtimes, and using it from non-async code.

§Examples

use asyncband::oneshot;

let (tx, rx) = oneshot::channel();

let sender = tokio::spawn(async move {
    tx.send(3).unwrap();
});

assert_eq!(rx.await, Ok(3));
sender.await.unwrap();

If the sender is dropped without sending, the receiver will fail with RecvError:

use asyncband::oneshot;

let (tx, rx) = oneshot::channel::<u32>();

drop(tx);

assert_eq!(rx.await, Err(oneshot::RecvError::Disconnected));

If the receiver is dropped before receiving, the sender will fail with SendError:

use asyncband::oneshot;

let (tx, rx) = oneshot::channel::<u32>();

drop(rx);

let error = tx.send(42).unwrap_err();
assert_eq!(error.into_inner(), 42);

§Cancellation

Awaiting a Receiver converts it into a Recv future that owns the receiving endpoint. Dropping either the receiver or its future disconnects the channel and discards any unread message.

To keep a pending receive alive when another branch wins, call Receiver::into_future before selecting and borrow the resulting future as &mut Recv.

Structs§

Receiver
Receives a value from the associated Sender.
Recv
A future that receives a value from the associated Sender, or returns RecvError if the sender is dropped without sending.
SendError
An error returned when trying to send on a disconnected channel. Returned from Sender::send if the corresponding Receiver has already been dropped.
Sender
Sends a value to the associated Receiver.

Enums§

RecvError
An error returned when awaiting the message via Receiver.
TryRecvError
Error returned by Receiver::try_recv.

Functions§

channel
Creates a new oneshot channel and returns the Sender and Receiver.