Stream — async iterator.
Using tokio-stream:
1use tokio_stream::StreamExt;2use tokio::sync::mpsc;34let (tx, mut rx) = mpsc::channel(32);56tokio::spawn(async move {7 for i in 0..5 {8 tx.send(i).await.unwrap();9 tokio::time::sleep(Duration::from_millis(100)).await;10 }11});1213while let Some(value) = rx.recv().await {14 println!("Received: {}", value);15}
Using async-stream:
1let stream = async_stream::stream! {2 for i in 0..5 {3 tokio::time::sleep(Duration::from_millis(100)).await;4 yield i;5 }6};78let values: Vec<i32> = stream.collect().await;
Key: Stream for async iteration.