16 releases

0.1.15 Mar 14, 2024
0.1.14 Apr 26, 2023
0.1.12 Feb 20, 2023
0.1.11 Oct 11, 2022
0.1.0 Dec 23, 2020

#258 in Asynchronous

Download history 838133/week @ 2023-12-06 808836/week @ 2023-12-13 562703/week @ 2023-12-20 453375/week @ 2023-12-27 787115/week @ 2024-01-03 821594/week @ 2024-01-10 928265/week @ 2024-01-17 936875/week @ 2024-01-24 1005831/week @ 2024-01-31 927785/week @ 2024-02-07 916205/week @ 2024-02-14 977305/week @ 2024-02-21 999962/week @ 2024-02-28 989988/week @ 2024-03-06 1037705/week @ 2024-03-13 871675/week @ 2024-03-20

4,086,066 downloads per month
Used in 5,167 crates (1,197 directly)

MIT license

2.5MB
39K SLoC

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 crate 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 as stream, 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.

Dependencies

~0–9.5MB
~61K SLoC