Search code examples
ruststreamrust-tokio

merging streams in rust / tokio


tokio has a Merge data structure which allows to "merge" two homogeneous streams and forget the provenance.

impl<T, U> Stream for Merge<T, U> where
    T: Stream,
    U: Stream<Item = T::Item>, { ...

Is there an algebraic pointwise tagged union for streams, which from a stream of a and a stream of b, produces a stream of Either a b ?

PS : I guess the answer is no as there is no standard sum type in rust apparently..


Solution

  • I don't think it's provided directly as a method in tokio, but you piece it together very simply yourself. There is no Either type in the Rust standard library but, like most other things, there's a crate for that.

    use either::Either; // 0.3.7
    use tokio::stream::StreamExt as _;
    
    stream1
        .map(Either::Left)
        .merge(stream2.map(Either::Right))