RRust By Example
advancedAsync

Async Streams

Use async streams for asynchronous iteration.

Async Streams

Use async streams for asynchronous iteration.

Difficulty

Advanced

Code

rust
use tokio_stream::StreamExt;
use tokio::time::{interval, Duration};

#[tokio::main]
async fn main() {
    let mut stream = tokio_stream::iter(vec![1, 2, 3, 4, 5])
        .map(|x| x * 2)
        .filter(|x| *x > 4);

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

Explanation

Streams are async iterators for sequences of values.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the async category to build a complete understanding of this topic.

Common Compiler Errors in This Topic

Use these error pages as a debugging companion while practicing this example category.

More Async Examples