Futures::stream::select but complete when 1 stream completes?

I want to pull from two streams at the same time, but stop when one of the two streams completes. Is that possible?

I tried using futures::stream::select, but it only completes if both underlying streams complete.

For example, I want to do something like this (I made up select_shorting):

use futures::stream::{ repeat, select_shorting, StreamExt };

let left = repeat(1).take(2);
let right = repeat(2);

let mut out = select_shorting(left, right);

assert_eq!(Some(1), out.next().await);
assert_eq!(Some(2), out.next().await);
assert_eq!(Some(1), out.next().await);
assert_eq!(None, out.next().await);

I am using futures 0.3.21.

It almost sounds like zip (Playground):

use futures::stream::{ iter, repeat, StreamExt };

let left = repeat(1).take(2);
let right = repeat(2);

let mut out = left.zip(right).flat_map(|(x, y)| iter([x, y]));

assert_eq!(Some(1), out.next().await);
assert_eq!(Some(2), out.next().await);
assert_eq!(Some(1), out.next().await);
assert_eq!(Some(2), out.next().await);
assert_eq!(None, out.next().await);

Note however, that this returns a final 2 from the right stream. In general, this is how I would your hypothetical select_shorting() to work, too, because there is no sure way to know whether a stream (or an iterator) expired without actually asking for the next element.

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.