如果我想将多个相同类型的流合并为一个,我会使用 Stream::select
:
let combined = first_stream.select(second_stream)
但是,一旦其中一个流耗尽,另一个流仍然可以为组合流产生结果。一旦任一基础流耗尽,我可以使用什么来耗尽组合流?
最佳答案
编写您自己的流组合器:
use futures::{Async, Poll, Stream}; // 0.1.25
struct WhileBoth<S1, S2>(S1, S2)
where
S1: Stream,
S2: Stream<Item = S1::Item, Error = S1::Error>;
impl<S1, S2> Stream for WhileBoth<S1, S2>
where
S1: Stream,
S2: Stream<Item = S1::Item, Error = S1::Error>,
{
type Item = S1::Item;
type Error = S1::Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
match self.0.poll() {
// Return errors or ready values (including the `None`
// that indicates the stream is empty) immediately.
r @ Err(_) | r @ Ok(Async::Ready(_)) => r,
// If the first stream is not ready, try the second one.
Ok(Async::NotReady) => self.1.poll(),
}
}
}
另见:
关于stream - 一旦其中一个底层流耗尽,就使流组合耗尽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53780368/