| 1 | A version of [async-stream](https://github.com/tokio-rs/async-stream) without macros. |
| 2 | This crate provides generic implementations of `Stream` trait. |
| 3 | `Stream` is an asynchronous version of `std::iter::Iterator`. |
| 4 | |
| 5 | Two functions are provided - `fn_stream` and `try_fn_stream`. |
| 6 | |
| 7 | # Usage |
| 8 | |
| 9 | ## Basic Usage |
| 10 | |
| 11 | If you need to create a stream that may result in error, use `try_fn_stream`, otherwise use `fn_stream`. |
| 12 | |
| 13 | To create a stream: |
| 14 | |
| 15 | 1. Invoke `fn_stream` or `try_fn_stream`, passing a closure (anonymous function). |
| 16 | 2. Closure will accept an `emitter`. |
| 17 | To return value from the stream, call `.emit(value)` on `emitter` and `.await` on its result. |
| 18 | Once stream consumer has processed the value and called `.next()` on stream, `.await` will return. |
| 19 | |
| 20 | ## Returning errors |
| 21 | |
| 22 | `try_fn_stream` provides some conveniences for returning errors: |
| 23 | |
| 24 | 1. Errors can be return from closure via `return Err(...)` or the question mark (`?`) operator. |
| 25 | This will end the stream. |
| 26 | 2. An `emitter` also has an `emit_err()` method to return errors without ending the stream. |
| 27 | |
| 28 | ## Limitations |
| 29 | |
| 30 | `fn_stream` does not support cross-task streams, that is all stream values must be produced in the same task as the stream. |
| 31 | Specifically, it is not supported to move `StreamEmitter` to another thread or tokio task. |
| 32 | If your use case necessitates this, consider using async chanells for that. |
| 33 | |
| 34 | ## Advanced usage |
| 35 | |
| 36 | Internal concurrency is supported within `fn_stream` (see [examples/join.rs](examples/join.rs)). |
| 37 | |
| 38 | # Examples |
| 39 | |
| 40 | Finite stream of numbers |
| 41 | |
| 42 | ```rust |
| 43 | use async_fn_stream::fn_stream; |
| 44 | use futures_util::Stream; |
| 45 | |
| 46 | fn build_stream() -> impl Stream<Item = i32> { |
| 47 | fn_stream(|emitter| async move { |
| 48 | for i in 0..3 { |
| 49 | // yield elements from stream via `emitter` |
| 50 | emitter.emit(i).await; |
| 51 | } |
| 52 | }) |
| 53 | } |
| 54 | ``` |
| 55 | |
| 56 | Read numbers from text file, with error handling |
| 57 | |
| 58 | ```rust |
| 59 | use anyhow::Context; |
| 60 | use async_fn_stream::try_fn_stream; |
| 61 | use futures_util::{pin_mut, Stream, StreamExt}; |
| 62 | use tokio::{ |
| 63 | fs::File, |
| 64 | io::{AsyncBufReadExt, BufReader}, |
| 65 | }; |
| 66 | |
| 67 | fn read_numbers(file_name: String) -> impl Stream<Item = Result<i32, anyhow::Error>> { |
| 68 | try_fn_stream(|emitter| async move { |
| 69 | // Return errors via `?` operator. |
| 70 | let file = BufReader::new(File::open(file_name).await.context("Failed to open file")?); |
| 71 | pin_mut!(file); |
| 72 | let mut line = String::new(); |
| 73 | loop { |
| 74 | line.clear(); |
| 75 | let byte_count = file |
| 76 | .read_line(&mut line) |
| 77 | .await |
| 78 | .context("Failed to read line")?; |
| 79 | if byte_count == 0 { |
| 80 | break; |
| 81 | } |
| 82 | |
| 83 | for token in line.split_ascii_whitespace() { |
| 84 | let Ok(number) = token.parse::<i32>() else { |
| 85 | // Return errors via the `emit_err` method. |
| 86 | emitter.emit_err( |
| 87 | anyhow::anyhow!("Failed to convert string \"{token}\" to number") |
| 88 | ).await; |
| 89 | continue; |
| 90 | }; |
| 91 | emitter.emit(number).await; |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | Ok(()) |
| 96 | }) |
| 97 | } |
| 98 | ``` |
| 99 | |
| 100 | # Why not `async-stream`? |
| 101 | |
| 102 | [async-stream](https://github.com/tokio-rs/async-stream) is great! |
| 103 | It has a nice syntax, but it is based on macros which brings some flaws: |
| 104 | * proc-macros sometimes interact badly with IDEs such as `rust-analyzer` or `RustRover`. |
| 105 | see e.g. <https://github.com/rust-lang/rust-analyzer/issues/11533> |
| 106 | * proc-macros may increase build times |