0

假设我有一个 Result<Vec> 流:

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

我怎样才能成为s具有返回类型的函数的返回值impl Stream<Item = Result<(), _>

4

1 回答 1

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.

于 2021-08-21T03:10:23.607 回答