| 1 | use async_fn_stream::fn_stream; |
| 2 | use futures_util::{pin_mut, Stream, StreamExt}; |
| 3 | |
| 4 | fn build_stream() -> impl Stream<Item = i32> { |
| 5 | fn_stream(|emitter| async move { |
| 6 | tokio::join!( |
| 7 | async { |
| 8 | for i in 0..3 { |
| 9 | // yield elements from stream via `emitter` |
| 10 | emitter.emit(i).await; |
| 11 | } |
| 12 | }, |
| 13 | async { |
| 14 | for i in 10..13 { |
| 15 | // yield elements from stream via `emitter` |
| 16 | emitter.emit(i).await; |
| 17 | } |
| 18 | } |
| 19 | ); |
| 20 | }) |
| 21 | } |
| 22 | |
| 23 | async fn example() { |
| 24 | let stream = build_stream(); |
| 25 | |
| 26 | pin_mut!(stream); |
| 27 | let mut numbers = Vec::new(); |
| 28 | while let Some(number) = stream.next().await { |
| 29 | print!("{number} "); |
| 30 | numbers.push(number); |
| 31 | } |
| 32 | println!(); |
| 33 | numbers.sort_unstable(); |
| 34 | assert_eq!(numbers, vec![0, 1, 2, 10, 11, 12]); |
| 35 | } |
| 36 | |
| 37 | #[tokio::main] |
| 38 | async fn main() { |
| 39 | futures_executor::block_on(example()); |
| 40 | } |