Sub topic 17
Streams: async sequences of values
A future produces one value. A stream produces many values over time, and you wait for each one. This chapter assumes you know async fn, .await, and Tokio basics from earlier chapters, plus ordinary Iterator use.
From Iterator to Stream
An Iterator has a next method that returns Option<Item> right away. A Stream is the async version. Its items arrive later, so asking for the next one takes an .await.
| Iterator | Stream |
|---|---|
| `next()` returns `Option<T>` | `next().await` returns `Option<T>` |
| Blocks the thread while waiting | Yields to the executor while waiting |
| In `std` | `Stream` trait in the `futures` crate (`futures-core`) |
Internally, Stream has a poll_next method. It works like Future::poll, but it returns Poll<Option<Item>>. Poll::Ready(Some(v)) is an item, Poll::Ready(None) ends the stream, and Poll::Pending means "not yet, I will wake you."
Consuming a stream
Add futures = "0.3" to Cargo.toml next to Tokio. Import StreamExt to get next and the adapter methods.
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. stream::iter turns any iterator into a stream. map is an adapter, like the iterator method of the same name. The stream must be mut because next takes &mut self.
Like futures, streams are lazy. Building the adapter chain does nothing until you call next().await.
Adapters that take async closures' results
StreamExt::map takes a plain closure. To run an async operation per item, use then. To run several at once, use buffered.
use futures::StreamExt;
use std::time::Duration;
use tokio::time::sleep;
async fn double(x: u32) -> u32 {
sleep(Duration::from_millis(100)).await;
x * 2
}
#[tokio::main]
async fn main() {
let results: Vec<u32> = futures::stream::iter(1..=4)
.map(double)
.buffered(2)
.collect()
.await;
println!("{results:?}");
}Here map(double) turns each number into a future. buffered(2) polls up to two of those futures at a time and keeps the output in input order. collect().await gathers everything into a Vec. This takes about 200 ms instead of 400 ms. Use buffer_unordered if order does not matter.
Common mistakes
- Forgetting
StreamExt. The error is "no method namednextfound". Importfutures::StreamExt(ortokio_stream::StreamExt). - Using
forloops. There is nofor awaitin stable Rust. Usewhile let Some(x) = s.next().await. - Calling
nexton a stream that is notUnpin. Some streams, such as ones built fromasyncblocks, must be pinned first. Usefutures::pin_mut!(s)orBox::pin(s).
Exercise
What is the difference between map(double) followed by buffered(2) and then(double), when double is an async function?
Show answer
then(double) runs the futures one at a time, so each item finishes before the next begins. map(double).buffered(2) polls up to two futures concurrently and still returns results in input order.
Exercise
What does s.next().await return when a stream has no more items?
Show answer
It returns None. The while let Some(v) = s.next().await loop then ends.