Runtime model

Streams are similar to futures, but instead of yielding a single value, theyasynchronously yield one or more values. They can be thought of as asynchronousiterators.

Just like futures, streams are able to represent a wide range of things as longas those things produce discrete values at different points sometime in thefuture. For instance:

  • UI Events caused by the user interacting with a GUI in different ways. When anevent happens the stream yields a different message to your app over time.
  • Push Notifications from a server. Sometimes a request/response model is notwhat you need. A client can establish a notification stream with a server to beable to receive messages from the server without specifically being requested.
  • Incoming socket connections. As different clients connect to a server, theconnections stream will yield socket connections.

The Stream trait

Just like Future, implementing Stream is common when using Tokio. Streamsyield many values, so lets start with a stream that generates the fibonacci sequence.

The Stream trait is as follows:

  1. trait Stream {
  2. /// The type of the value yielded by the stream.
  3. type Item;
  4. /// The type representing errors that occurred while processing the computation.
  5. type Error;
  6. /// The function that will be repeatedly called to see if the stream has
  7. /// another value it can yield
  8. fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error>;
  9. }

The Item associated type is the type yielded by the stream. The Errorassociated type is the type of the error yielded when something unexpectedhappens. The poll function is very similar to Future’s poll function. Theonly difference is that, this time, Option<Self::Item> is returned.

Stream implementations have the poll function called many times. When the nextvalue is ready, Ok(Async::Ready(Some(value))) is returned. When the stream isnot ready to yield a value, Ok(Async::NotReady) is returned. When thestream is exhausted and will yield no further values, Ok(Async::Ready(None))is returned.

Next up: I/O Overview