Function async_fn_stream::try_fn_stream
source · [−]pub fn try_fn_stream<T: Send, E: Send, Fut: Future<Output = Result<(), E>>>(
func: impl FnOnce(StreamEmitter<T>) -> Fut
) -> TryFnStream<T, E, Fut>
Expand description
Create a new fallible stream which is implemented by func
.
Caller should pass an async function which will return successive stream elements via StreamEmitter::emit
or returns errors as Result::Err
.
Example
use async_fn_stream::try_fn_stream;
use futures::Stream;
fn build_stream() -> impl Stream<Item = Result<i32, anyhow::Error>> {
try_fn_stream(|emitter| async move {
for i in 0..3 {
// yield elements from stream via `emitter`
emitter.emit(i).await;
}
// return errors as `Result::Err`
Err(anyhow::anyhow!("An error happened"))
})
}