Skip to main content

async_try_stream

Function async_try_stream 

Source
pub fn async_try_stream<T, E, F: Future<Output = Result<(), E>>>(
    generator: impl FnOnce(TryEmitter<T, E>) -> F,
) -> impl FusedStream<Item = Result<T, E>>
Expand description

Creates a fallible Stream from an async generator function.

The generator closure receives a TryEmitter<T, E> and runs as an async block that returns Result<(), E>. Each emitter.emit(value).await call suspends the generator and produces Ok(value) as the next stream item. The ? operator can be used inside the generator to short-circuit on errors: the error is emitted as the final Err(e) item and the stream ends. The stream also ends when the generator future resolves to Ok(()).

ยงExample

use datafusion_execution::async_try_stream;
use futures::StreamExt;

let stream = async_try_stream(|mut emitter| async move {
    emitter.emit(1_i32).await;
    emitter.emit(2_i32).await;
    Err::<(), _>("something went wrong")?;
    emitter.emit(3_i32).await; // never reached
    Ok(())
});

let values: Vec<Result<i32, &str>> = stream.collect().await;
assert_eq!(values, vec![Ok(1), Ok(2), Err("something went wrong")]);