[][src]Function stream_generator::generate_try_stream

pub fn generate_try_stream<T, E, F, R>(
    generator: F
) -> impl Stream<Item = Result<T, E>> where
    F: FnOnce(Yielder<Result<T, E>>) -> R,
    R: Future<Output = Result<(), E>>, 

Creates a stream of Results from generator.

generator will receive a yielder object as an argument and should return a future (usually an async block) that will produce the stream's values using the yielder. If the future finishes with an Ok, the stream will end after producing all yielded values. If the future finishes with an Err, the stream will end after producing all yielded values and then producing an Err returned by the future. If the future never finishes, the stream will also never finish.

use futures::stream::StreamExt;
use stream_generator::generate_try_stream;

async fn failing() -> Result<(), &'static str> {
    Err("world")
}

#[tokio::main]
async fn main() {
    let s = generate_try_stream(|mut y| async move {
        y.send(Ok("hello")).await;
        failing().await?;
        unreachable!();
    });

    let values: Vec<_> = s.collect().await;
    assert_eq!(values, vec![Ok("hello"), Err("world")]);
}