Skip to main content

Module oneshot

Module oneshot 

Source
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();

tokio::spawn(async move {
    if let Err(_) = tx.send(3) {
        println!("the receiver dropped");
    }
});

match rx.await {
    Ok(v) => println!("got = {:?}", v),
    Err(_) => println!("the sender dropped"),
}

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

use asyncband::oneshot;

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

tokio::spawn(async move { drop(tx) });

match rx.await {
    Ok(_) => panic!("This doesn't happen"),
    Err(_) => println!("the sender dropped"),
}

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

use asyncband::oneshot;

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

drop(rx);

match tx.send(42) {
    Ok(_) => panic!("This doesn't happen"),
    Err(_) => println!("the receiver dropped"),
}

Structs§

Receiver
Receives a value from the associated Sender.
Recv
A future that completes when the message is sent from the associated Sender, or the Sender is dropped before sending a message.
SendError
An error returned when trying to send on a closed 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.