One-shot

The oneshot module implements a channel of a single message. It also has its own Sender and Receiver types, but these work in a different way. The Sender has a send method that completes oneshot and consumes an instance completely. Sender doesn't need to implement the Sink trait, because we can't send multiple items. It has a preallocated cell for an item that will be put into the cell immediately and we don't have any queue.

The Receiver implements the Future trait, which means you have to use a reactor to get an item from it:

fn single() {
let (tx_sender, rx_future) = oneshot::channel::<u8>();
let receiver = rx_future.map(|x| {
println!("Received: {}", x);
});
let sender = tx_sender.send(8);
let execute_all = future::join_all(vec![
to_box(receiver),
to_box(sender),
]).map(drop);
tokio::run(execute_all);
}

In this example, we created a Sender and a Receiver for a oneshot channel. The sender is an object that will be consumed with the send method call. The Receiver implements the Future trait and we can use the map method to get access to a value.

Previously, we mentioned that we can send messages to Sink from multiple sources. Let's implement this example using channels.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.176.228