expression

Axum: generate response pieces on demand

unfold keeps state between yielded items. Returning None ends the stream. This finite counter generates records one at a time instead of first building a vector of records. Real sources must still bound buffering and handle cancellation. In-memory standalone Cargo example. Expected stdout (not executed): 1 2 3 Common mistake: Forgetting the termination condition in a finite report stream.

Formal Syntax & Structure

rust syntaxrust
stream::unfold(state, |state| async move { ... })

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::body::Bytes;    use futures_util::stream;    use std::convert::Infallible;    let chunks = stream::unfold(1, |n| async move {        if n > 3 { None } else { Some((Ok::<_, Infallible>(Bytes::from(format!("{n}\n"))), n + 1)) }    });    let bytes = to_bytes(Body::from_stream(chunks), 32).await.unwrap();    print!("{}", std::str::from_utf8(&bytes).unwrap());}
Rust Reference