0

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<(), _>?

Kafji
  • 31
  • 5

1 Answers1

3

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.

Kafji
  • 31
  • 5
  • 1
    s.map_ok(|x| stream::iter(x.into_iter().map(Ok))).try_flatten() ? – Jeff Garrett Aug 21 '21 at 21:24
  • @JeffGarrett That works. Thanks! [Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=202f835791552d6d4ac2ba3145fe4669) – Kafji Aug 31 '21 at 10:12