pub fn either<O, S1, S2>(s1: S1, s2: S2) -> RS2Stream<O>Expand description
Select between two streams based on which one produces a value first
This combinator takes two streams and emits values from whichever rs2_stream produces a value first. Once a value is received from one rs2_stream, the other rs2_stream is cancelled. If either rs2_stream completes (returns None), the combinator switches to the other rs2_stream exclusively.
ยงExamples
use rs2_stream::rs2::*;
use std::time::Duration;
use async_stream::stream;
use tokio::time::sleep;
use futures_util::stream::StreamExt;
// Create two streams with different timing
let fast_stream = stream! {
yield 1;
sleep(Duration::from_millis(10)).await;
yield 2;
sleep(Duration::from_millis(100)).await;
yield 3;
};
let slow_stream = stream! {
sleep(Duration::from_millis(50)).await;
yield 10;
sleep(Duration::from_millis(10)).await;
yield 20;
};
// The either combinator will select values from whichever rs2_stream produces first
let result = either(fast_stream.boxed(), slow_stream.boxed())
.collect::<Vec<_>>()
.await;
// We expect to get values from the fast rs2_stream first, then from the slow rs2_stream
// when the fast rs2_stream is waiting longer
assert_eq!(result, vec![1, 2, 10, 20]);