Module tokio::sync::oneshot[][src]

This is supported on crate feature sync 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 handle pair that form the channel.

The Sender handle is used by the producer to send the value. The Receiver handle is used by the consumer to receive the value.

Each handle can be used on separate tasks.

Examples

use tokio::sync::oneshot;

#[tokio::main]
async fn main() {
    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 error::RecvError:

use tokio::sync::oneshot;

#[tokio::main]
async fn main() {
    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"),
    }
}

Modules

Oneshot error types

Structs

Receive a value from the associated Sender.

Sends a value to the associated Receiver.

Functions

Create a new one-shot channel for sending single values across asynchronous tasks.