How it works...

Within our send_example() function:

  • On lines 13 through 15, we set up three oneshot channels.
  • On lines 20 through 23 we use futures::stream::futures_ordered, which will convert a list (any IntoIterator value) of futures into a Stream yielding results on a first in, first out (FIFO) basis. If any underlying futures do not complete before the next future is invoked, this function will wait until the long-running future has been completed and will then internally re-sort that future into its proper order.
  • Line 25 shows us that we can push additional futures into the futures_ordered iterator separately.
  • Line 28 demonstrates another function that doesn't rely on sorting on a FIFO basis, called futures::stream::futures_unordered. This function will have better performance than its counterpart futures_ordered, but for our example, we are not sending enough values to make a difference.
  • On lines 31 through 33 we send values to our channels, mimicking the process of returning values from an API, a database, and so on. If the send is successful then Ok(()) will be returned, otherwise, an Err type will be returned.
  • And on our last two lines (35 and 36), we collect our futures_ordered values and display them to the console.

Next, the check_if_closed() function:

  • Our channel should remain open until we explicitly drop/destroy the receiver (or send a value to the channel). We can check the status of our receiver by invoking the futures::channel::oneshot::Sender::is_canceled(&self) -> bool function, which we have done on lines 42 and 45.

Then the check_if_ready() function:

  • On line 50 we explicitly assign a value to the oneshot's receiver, which would put our receiver in a state of pending (since it already has a value).
  • We drop our receiver on line 55 and we can check if our receiver is ready by using our sender's futures::channel::oneshot::Sender::poll_cancel function, which we use on lines 57 and 58. poll_cancel will return Ok(Async::Ready) if the receiver has been dropped or Ok(Async::Pending) if the receiver has not been dropped.
..................Content has been hidden....................

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