Using the Stream trait

Stream is a trait that represents a sequence of deferred items. It works in a similar way to the Iterator trait, but it uses the poll method to get the next Item or to return Error in the case of failure. The stream can either be incoming data from a socket or data that can be read from a file. Stream can be converted to Future and vice versa if the Future instance returns a Stream.

To use streams effectively, you should learn the methods of the StreamExt trait. This lets you make a chain to process every item of the stream or even join multiple streams into one. For example, you can filter some elements from Stream using the filter method with a predicate:

let stream = stream::iter_ok::<_, ()>(vec![-1, 0, 1, 2, 3]);
let filtered_stream = stream.filter(|x| x > 0);

The iter_ok method creates a Stream from the Iterator. It is useful if you want to provide your own values from a Vec instance.

A useful feature is the conversion of a Future instance that contains a Stream as a result to just a Stream. For example, when you try to connect by TCP using the TcpStream::connect method of the tokio crate, it will return ConnectFuture, which implements the Future trait and returns a TcpStream instance.

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

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