stream - 一旦其中一个底层流耗尽,就使流组合耗尽

标签 stream rust future

如果我想将多个相同类型的流合并为一个,我会使用 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/

相关文章:

rust - 这个错误是由于编译器对 RefCell 的特殊了解吗?

asynchronous - Dart 中事件循环何时启动以及事件队列如何工作

Scala:忽略 Future 返回值,但将它们链接起来

asynchronous - 如何有条件地退还不同类型的 future ?

rust - 为什么std::vec::Vec实现两种Extend特性?

android - 将 Android 截屏流式传输到 PC

c++ - 在 C++ 高效存储上,刷新文件策略

c# - 在 ASP.NET MVC 中将 FileShare.ReadWrite 与 HttpPostedFile 结合使用

rust - 从另一个 crate 的类型上实现 std::convert::From

捕获 stdin、stdout、stderr 上的错误