Sub topic 18
Streams: async sequences of values
This chapter assumes you can write async fn, use .await, spawn Tokio tasks, and read trait definitions that involve Pin<&mut Self>. It covers the Stream trait, how to consume and build streams, and the mistakes people commonly make with them.
What a stream is
A future produces one value, eventually. A stream produces zero or more values over time and then ends. You can think of it as an async version of Iterator.
The trait looks like this. This is a copy of the futures crate's definition under another name, so it compiles on its own.
use std::pin::Pin;
use std::task::{Context, Poll};
trait MyStream {
type Item;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>;
}poll_next has three outcomes:
| Return value | Meaning |
|---|---|
| `Poll::Ready(Some(item))` | The next item is available. |
| `Poll::Pending` | No item yet. The stream has stored the waker from `cx` and will wake the task later. |
| `Poll::Ready(None)` | The stream is finished. |
The real Stream trait lives in the futures-core crate, re-exported by futures and tokio-stream. The standard library has no stable stream trait yet. Add these dependencies for the examples in this chapter:
[dependencies]
tokio = { version = "1", features = ["full"] }
futures = "0.3"
tokio-stream = "0.1"Consuming a stream
You rarely call poll_next yourself. The StreamExt extension trait adds next(), which returns a future that resolves to the next Option<Item>. Rust has no for await loop, so the standard pattern is while let:
use futures::StreamExt;
#[tokio::main]
async fn main() {
let mut s = futures::stream::iter(1..=3).map(|x| x * 2);
while let Some(v) = s.next().await {
println!("{v}");
}
}This prints 2, 4 and 6. Like iterators, streams are lazy. Building the map chain does no work. Items are produced only while a consumer awaits next().
Writing a stream by hand
A hand-written stream shows the contract. This one is always ready, so it never needs the waker:
use futures::{Stream, StreamExt};
use std::pin::Pin;
use std::task::{Context, Poll};
struct Countdown {
remaining: u32,
}
impl Stream for Countdown {
type Item = u32;
fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<u32>> {
if self.remaining == 0 {
Poll::Ready(None)
} else {
let n = self.remaining;
self.remaining -= 1;
Poll::Ready(Some(n))
}
}
}
#[tokio::main]
async fn main() {
let mut c = Countdown { remaining: 3 };
while let Some(n) = c.next().await {
println!("{n}");
}
}The output is 3, 2, 1. Mutating self.remaining through Pin<&mut Self> compiles because Countdown is Unpin. If a stream returns Pending, it must first arrange for cx.waker() to be woken. Otherwise the task sleeps forever.
Building streams without implementing the trait
Most streams come from existing sources or from helper constructors.
futures::stream::iterturns anyIntoIteratorinto a stream that is always ready.futures::stream::unfoldbuilds a stream from a state value and an async closure.tokio_stream::wrappers::ReceiverStreamwraps atokio::sync::mpsc::Receiver. Other wrappers exist forBroadcastStream,IntervalStreamandTcpListenerStream.
A channel is the most common source of a stream. The spawned task produces values, and the consumer filters them:
use tokio::sync::mpsc;
use tokio_stream::{wrappers::ReceiverStream, StreamExt};
#[tokio::main]
async fn main() {
let (tx, rx) = mpsc::channel::<u32>(4);
tokio::spawn(async move {
for i in 0..6 {
tx.send(i).await.unwrap();
}
});
let mut evens = ReceiverStream::new(rx).filter(|n| n % 2 == 0);
while let Some(n) = evens.next().await {
println!("even {n}");
}
}The loop ends when the sender is dropped and recv returns None. The channel is bounded, so a slow consumer makes tx.send(..).await wait. This is backpressure, and it comes from the pull-based design. A stream only produces what the consumer asks for.
Pinning and Unpin
StreamExt::next requires Self: Unpin. Streams built from async blocks or closures, such as the one unfold returns, usually are not Unpin, because they hold a future that may be self-referential. You have two ways to pin them:
use futures::{pin_mut, stream, StreamExt};
#[tokio::main]
async fn main() {
let s = stream::unfold(0u32, |n| async move {
if n < 3 {
Some((n, n + 1))
} else {
None
}
});
pin_mut!(s);
while let Some(v) = s.next().await {
println!("{v}");
}
}pin_mut! pins the stream on the stack. For a stream you need to move or store, use Box::pin(s), which produces a Pin<Box<_>> that is Unpin. If you see an error saying that Unpin is not implemented for some impl Stream type, this is the fix.
Concurrency inside a stream
Combinators such as map, filter and take process one item at a time. To run async work concurrently, map each item to a future and then use buffered or buffer_unordered:
use futures::{stream, StreamExt};
use std::time::Duration;
use tokio::time::sleep;
async fn fetch(id: u32) -> u32 {
sleep(Duration::from_millis(100 * (5 - id as u64))).await;
id
}
#[tokio::main]
async fn main() {
let results: Vec<u32> = stream::iter(1..=3)
.map(fetch)
.buffer_unordered(2)
.collect()
.await;
println!("{results:?}");
}At most two fetch futures run at once. Fetch 1 takes 400 ms, fetch 2 takes 300 ms, and fetch 3 starts when fetch 2 finishes. The result is [2, 1, 3], in completion order. buffered(2) runs the same futures concurrently but yields results in input order, which gives [1, 2, 3] at the cost of holding finished results back. The buffer size is your concurrency limit, so choose it deliberately for network calls.
Common errors
- Mixing extension traits.
futures::StreamExtandtokio_stream::StreamExtboth definenext,mapandfilter. Importing both causes ambiguity errors. Import one, or call the methods with explicit paths. - Polling after the end. A stream may panic or misbehave if polled again after it returns
None. Call.fuse()when you use a stream in aselect!loop. - Blocking inside a combinator. Closures passed to
maprun on the executor thread. Blocking work there stalls other tasks, as described in the chapter on blocking code. - Holding a lock across items. A
MutexGuardkept alive across an.awaitinside a loop serialises everything that needs the lock.
Exercise
A stream of 100 URLs is mapped to an async download function. You want at most 10 downloads running at once, and you want results in the same order as the URLs. Which combinator do you use, and what is the trade-off compared with buffer_unordered(10)?
Show answer
Use .map(download).buffered(10). It keeps up to 10 futures running and yields results in input order. The trade-off is that a slow early download holds back finished later ones until it completes, so they sit in memory and the consumer sees them later. buffer_unordered(10) yields each result as soon as it finishes, which gives lower latency per item but a different order.
Exercise
Why does futures::stream::unfold(...) followed by .next().await fail to compile, and what are two ways to fix it?
Show answer
StreamExt::next requires the stream to be Unpin, and the stream returned by unfold holds an async-block future that is not Unpin. Fix it by pinning the stream on the stack with futures::pin_mut!(s), or by boxing it with let mut s = Box::pin(s);.