expression
Axum: end a response stream cooperatively
Long-lived response streams need a way to stop when the application shuts down. This finite in-memory model emits one record and then waits for a one-way shutdown notification before ending. Treat channel closure as a stop signal. Production streams must also handle client disconnects and define a bounded drain policy. In-memory standalone Cargo example. Expected stdout (not executed): stream ended Common mistake: Waiting indefinitely for a never-ending stream while draining a server.
Formal Syntax & Structure
rust syntaxrust
watch::Receiver::changed().awaitWorking 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, StreamExt}; use std::convert::Infallible; let (tx, rx) = tokio::sync::watch::channel(false); let chunks = stream::unfold((false, rx), |(sent, mut rx)| async move { if *rx.borrow() { return None; } if !sent { return Some((Ok::<_, Infallible>(Bytes::from_static(b"ready")), (true, rx))); } while !*rx.borrow() { if rx.changed().await.is_err() { break; } } None }); let mut data = Body::from_stream(chunks).into_data_stream(); assert_eq!(&data.next().await.unwrap().unwrap()[..], b"ready"); tx.send(true).unwrap(); assert!(data.next().await.is_none()); println!("stream ended");}