Function async_fn_stream::try_fn_stream
source · pub fn try_fn_stream<T, E, Fut: Future<Output = Result<(), E>>>(
func: impl FnOnce(TryStreamEmitter<T, E>) -> Fut
) -> TryFnStream<T, E, Fut>
Expand description
Create a new fallible stream which is implemented by func
.
Caller should pass an async function which can:
- return successive stream elements via
StreamEmitter::emit
- return transient errors via [
StreamEmitter::emit_err
] - return fatal errors as
Result::Err
§Example
use async_fn_stream::try_fn_stream;
use futures_util::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 view emitter without ending the stream
emitter.emit_err(anyhow::anyhow!("An error happened"));
// return errors from stream, ending the stream
Err(anyhow::anyhow!("An error happened"))
})
}