Learn Tokio · 10/14

Streams: Asynchronous Iterators

6 min read

Welcome to the deep end of the pool! 🏊‍♂️ Today we are talking about Streams.

If you are comfortable with Rust's Iterator trait (things you can call .next() on or use in a for loop), you are halfway there. But in the world of high-performance network programming, standard iterators have a fatal flaw: they are synchronous.

Imagine you are iterating over a list of URLs to download. If you use a standard Iterator, your code blocks and waits for the first download to finish before it even thinks about asking for the second one. That’s like a waiter refusing to take anyone else's order until the first customer has finished eating their dessert. 🍰

Tokio Streams solve this. They are Iterators that can await.


🛠️ Setup & Boilerplate

Before we dive in, let's make sure your Cargo.toml is ready for industry standards. Tokio splits its stream functionality into a separate crate to keep the core lightweight.

toml
[dependencies]
tokio = { version = "1", features = ["full"] }
tokio-stream = "0.1"
futures = "0.3" # Often needed for additional stream combinators

Note: In production, always check crates.io for the absolute latest semantic version.


1. Stream Trait: Understanding the Async Version of Iterator

The Definition

A Stream is a sequence of values produced asynchronously over time.

The Problem

Standard Rust Iterators look like this:

rust
pub trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
}

When you call next(), it returns a value immediately. But what if the data isn't ready? What if it's coming from a TCP socket or a file read? If next() blocks the thread waiting for data, the Tokio runtime (and all other tasks on that thread) halts.

The Solution

The Stream trait allows the runtime to check if data is ready. If not, it yields control back to the scheduler (just like a Future).

Here is the simplified definition of the Stream trait:

rust
use std::pin::Pin;
use std::task::{Context, Poll};

pub trait Stream {
    type Item;

    // Look familiar? It's like Future::poll, but for a sequence!
    fn poll_next(
        self: Pin<&mut Self>, 
        cx: &mut Context<'_>
    ) -> Poll<Option<Self::Item>>;
}

Key Takeaways:

  1. poll_next: Instead of next, we have poll_next. It returns Poll::Pending (not ready yet) or Poll::Ready(Some(value)) (here is data) or Poll::Ready(None) (stream finished).
  2. Pinning: You see Pin<&mut Self>. Because streams involve asynchronous state machines, they generally need to be "pinned" to a location in memory so their internal references don't break while waiting.

Fun Fact: Rust originally debated calling this trait AsyncIterator. However, Stream was chosen because it represents data "streaming" in over time.


2. The tokio-stream Crate: Essential Tools and Extensions

The Problem

The Stream trait is technically defined in the futures crate (and eventually the standard library), but Tokio's core doesn't include all the fancy utility methods (like map, filter, next) by default to save compile time.

The Solution

The tokio-stream crate provides the StreamExt (Stream Extension) trait. This is the "Swiss Army Knife" for streams. Without this, you cannot easily iterate or transform streams.

It also provides wrappers to convert standard types into Streams.

Industry Example: A Simple Interval Stream

One of the most common uses of a stream is a timer that ticks periodically.

rust
use tokio_stream::{self as stream, StreamExt}; // Import StreamExt!
use std::time::Duration;

#[tokio::main]
async fn main() {
    // A stream that yields '()' every 100ms
    let mut interval_stream = stream::iter(0..3).map(|i| {
        // Simulating a stream creator here for demonstration
        i
    });
    
    // In real Tokio usage, we usually use tokio::time::interval which acts like a stream
    let mut interval = tokio::time::interval(Duration::from_millis(100));

    // We can consume the first 3 ticks
    for _ in 0..3 {
        interval.tick().await; 
        println!("Tick! ⏰");
    }
}

3. Consuming Streams: Iterating and Processing Items

The Problem

You cannot use a for loop on a Stream.

rust
// ❌ THIS WILL NOT COMPILE
// for item in my_stream { ... }

Rust's for loop only works on synchronous Iterators. The compiler doesn't know how to await inside the loop mechanism itself.

The Solution

There are two industry-standard ways to consume a stream.

Method A: while let with .next().await

This is the manual, granular way. To use .next(), the stream must be Pinned.

rust
use tokio_stream::{self as stream, StreamExt};

#[tokio::main]
async fn main() {
    // Create a stream from a vector
    let mut stream = stream::iter(vec![1, 2, 3]);

    // We must await the next item
    while let Some(value) = stream.next().await {
        println!("Received: {}", value);
    }
}

Note: stream::iter creates a stream that is already Unpin (safe to move), so we don't need to manually pin it. For more complex streams, you might need tokio::pin!(stream);.

Method B: StreamExt helpers

Often, you just want to collect results into a collection.

rust
let numbers: Vec<i32> = stream.collect().await;

4. Adapters: Mapping, Filtering, and Transforming Data

The Problem

Raw streams often deliver data in a format you don't want (e.g., raw bytes from a TCP socket), or they deliver too much data. You want to transform or filter this data while it flows, without collecting it all into a huge vector first.

The Solution

Just like standard Iterators, Streams have adapters.

Crucial Distinction:

  1. map: Used for synchronous computations (e.g., parsing an integer).
  2. then: Used for asynchronous computations (e.g., taking an ID from the stream and querying a database).

Hands-on Example: The Data Pipeline

Imagine a system that emits User IDs. We want to:

  1. Filter out ID 0 (admin).
  2. Format them into strings.
  3. Process them.
rust
use tokio_stream::{self as stream, StreamExt};

#[tokio::main]
async fn main() {
    let user_ids = vec![0, 101, 102, 103];
    let stream = stream::iter(user_ids);

    let mut processed_stream = stream
        // 1. FILTER: Synchronous predicate
        .filter(|&id| id != 0) 
        
        // 2. MAP: Synchronous transformation
        .map(|id| format!("User_{}", id))
        
        // 3. THEN: Asynchronous work (simulating a DB call or API req)
        // 'then' takes a closure that returns a Future
        .then(|user_tag| async move {
            // Simulate network delay
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
            format!("{} is active", user_tag)
        });

    // 4. CONSUME
    // We pin the stream to iterate over it
    tokio::pin!(processed_stream);

    while let Some(status) = processed_stream.next().await {
        println!("Report: {}", status);
    }
}

Common Adapters Cheat Sheet

Adapter Description Sync/Async?
`.map( x ...)`
`.filter( x ...)`
.take(n) Takes only first n items. N/A
`.then( x async { ... })`
`.fold(init, acc, x ...)`

Imagination Time: Think of .map as a worker stamping a label on a box passing on a conveyor belt. It's fast. Think of .then as a worker taking the box off the belt, walking into another room to paint it, and bringing it back. The belt (stream) waits or handles the concurrency depending on how you configure it (e.g., buffer_unordered).


Summary

  1. Streams are asynchronous Iterators. They return Poll::Ready(Some(val)) or Poll::Pending.
  2. tokio-stream is the crate you need to make streams usable.
  3. Use while let Some(v) = stream.next().await to iterate.
  4. Use map for CPU logic and then for async logic (API calls/DB) inside a stream pipeline.

Streams are the backbone of reactive systems in Rust. Whether you are handling WebSockets, TCP traffic, or database rows, you are likely swimming in a Stream. 🌊


🔗 References & Further Reading

Challenge

You are building an asynchronous data processing pipeline to fetch user data. Your task is to process a stream of user IDs from 1 to 10.

  1. Create a stream from an iterator that yields numbers from 1 to 10 inclusive. You can use the stream::iter function for this.
  2. Chain stream adapters to perform the following transformations in order:
    a. Filter the stream, keeping only the odd-numbered IDs.
    b. For each remaining odd-numbered ID, use an asynchronous adapter to call the provided fetch_user_data function. This function simulates a non-blocking database call.
  3. Consume the resulting stream of user data strings using a while let Some(...) loop.
  4. Inside the loop, print each user data string to the console.

Constraints:

  • You must use the while let loop pattern to consume the stream.
  • Do not use stream.collect().await.

Expected result

The program should output the user records for all odd-numbered IDs between 1 and 10. The output must be printed to the console in the exact order shown below:

crmsh
User record for id #1
User record for id #3
User record for id #5
User record for id #7
User record for id #9
rust

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.