Kafji
Kafji

Reputation: 31

Convert Stream<Item = Result<Vec<T>, _>> to Stream<Item = Result<T>>

Suppose I have a stream of Result<Vec>:

let v = Ok(vec![(), ()]);
let s = stream::once(future::ready(v));

How can I make s be the return value of a function with return type impl Stream<Item = Result<(), _>?

Upvotes: 0

Views: 1129

Answers (1)

Kafji
Kafji

Reputation: 31

The best solution I have is to use flat_map, pattern match the Result, and boxed the streams.

fn units() -> impl TryStream<Ok = (), Error = ()> {
  let v = Ok(vec![(), ()]);
  let s = stream::once(future::ready(v));
  s.flat_map(|x: Result<Vec<_>, _>| match x {
      Ok(x) => stream::iter(x).map(|x| Ok(x)).boxed(),
      Err(x) => stream::once(future::ready(Err(x))).boxed(),
  })
}

Edit:
See Jeff Garrett's comment for a non boxed solution.

Upvotes: 3

Related Questions