[][src]Module tokio::stream

This is supported on crate feature stream only.

Stream utilities for Tokio.

A Stream is an asynchronous sequence of values. It can be thought of as an asynchronous version of the standard library's Iterator trait.

This module provides helpers to work with them. For examples of usage and a more in-depth description of streams you can also refer to the streams tutorial on the tokio website.

Iterating over a Stream

Due to similarities with the standard library's Iterator trait, some new users may assume that they can use for in syntax to iterate over a Stream, but this is unfortunately not possible. Instead, you can use a while let loop as follows:

use tokio::stream::{self, StreamExt};

#[tokio::main]
async fn main() {
    let mut stream = stream::iter(vec![0, 1, 2]);

    while let Some(value) = stream.next().await {
        println!("Got {}", value);
    }
}

Returning a Stream from a function

A common way to stream values from a function is to pass in the sender half of a channel and use the receiver as the stream. This requires awaiting both futures to ensure progress is made. Another alternative is the async-stream crate, which contains macros that provide a yield keyword and allow you to return an impl Stream.

Conversion to and from AsyncRead/AsyncWrite

It is often desirable to convert a Stream into an AsyncRead, especially when dealing with plaintext formats streamed over the network. The opposite conversion from an AsyncRead into a Stream is also another commonly required feature. To enable these conversions, [tokio-util] provides the StreamReader and ReaderStream types when the io feature is enabled.

Re-exports

pub use futures_core::Stream;

Structs

Emptystream

Stream for the empty function.

Iterstream

Stream for the iter function.

Oncestream

Stream for the once function.

Pendingstream

Stream for the pending function.

StreamMapstream

Combine many streams into one, indexing each source stream with a unique key.

Traits

FromStreamstream

Convert from a Stream.

StreamExtstream

An extension trait for Streams that provides a variety of convenient combinator functions.

Functions

emptystream

Creates a stream that yields nothing.

iterstream

Converts an Iterator into a Stream which is always ready to yield the next value.

oncestream

Creates a stream that emits an element exactly once.

pendingstream

Creates a stream that is never ready