Early termination of a stream::unfold

I have a stream::unfold and overall it is working fine. it is something like this from an earlier post:

The example shows this:

let stream = stream::unfold(0, |state| async move {
    if state <= 2 {
        let next_state = state + 1;
        let yielded = state  * 2;
        Some((yielded, next_state))
    } else {
        None
    }
});

I need to terminate the stream prematurely in some cases. Because the ending return value is None I thought by using something like this I could do it:

if a == 0 {
  return None;
}

But it does not stop the stream loop, it just continues forever. In other cases I'd like to return a valid value early too but I suspect that won't work either.

Is there a way to do this?

What is a and where do you want to write that code? You can make it terminate from the inside of the stream, as well as from the outside, just don't call .next() anymore.

If the closure returns None instead of Some(Future) , then the unfold() will stop producing items and return Poll::Ready(None) in future calls to poll() .

The code you posted is from unfold in futures::stream - Rust and your code reading the stream should be like this

while let Some(x) = stream.next().await {
    // ...
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.