Skip to content

try_stream! / stream! with error close stream #81

@BratSinot

Description

@BratSinot

Greetings!

Why Err close stream? I can't use .filter(..) in that case.

use async_stream::{stream, try_stream};
use futures_util::{pin_mut, Stream, StreamExt};
use std::future::ready;

fn error_or_ok(rcx: usize) -> Result<usize, String> {
    if rcx % 2 == 0 {
        Ok(rcx)
    } else {
        Err(format!("Error{rcx}"))
    }
}

fn return_stream() -> impl Stream<Item = Result<usize, String>> {
    //stream! {
    try_stream! {
        let mut rcx = 0usize;
        loop {
            //yield Ok(error_or_ok(rcx)?); // with stream! closes
            //yield {move || { Ok(error_or_ok(rcx)?) }}(); // with stream! ok
            yield error_or_ok(rcx)?; // with try_stream! closes
            rcx += 1;
        }
    }
    .filter(|data| {
        let ret = if let Err(error) = data {
            eprintln!("Got error: `{error}`.");
            false
        } else {
            true
        };

        ready(ret)
    })
}

#[tokio::main]
async fn main() {
    let stream = return_stream();
    pin_mut!(stream);

    println!("Some: `{:?}`", stream.next().await);
    println!("None: `{:?}`", stream.next().await);
    println!("Some: `{:?}`", stream.next().await);
    println!("None: `{:?}`", stream.next().await);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions