如果流为空(需要等待下一个元素),有没有办法使 StreamExt::next 非阻塞(快速失败)?

Is there a way to make StreamExt::next non blocking (fail fast) if the stream is empty (need to wait for the next element)?

目前我正在做这样的事情

use tokio::time::timeout;

while let Ok(option_element) = timeout(Duration::from_nanos(1), stream.next()).await {
...
}

排空流的 rx 缓冲区中已有的项目。我不想等待下一个没有收到的元素

我认为超时会减慢 while 循环。

我想知道是否有更好的方法可以在不使用超时的情况下执行此操作? 可能像这样 https://github.com/async-rs/async-std/issues/579 但对于 futures/tokio.

中的流

您问题的直接答案是使用期货箱中的 FutureExt::now_or_never 方法,如 stream.next().now_or_never()

然而,通过在循环中的每个事物上调用 now_or_never 来避免编写等待多个事物的繁忙循环是很重要的。这很糟糕,因为它阻塞了线程,您应该更喜欢不同的解决方案,例如 tokio::select! to wait for multiple things. For the special case of this where you are constantly checking whether the task should shut down, see

另一方面,使用 now_or_never 非常合适的一个示例是当您想要清空当前可用项目的队列以便以某种方式批处理它们时。这很好,因为 now_or_never 循环将在清空队列后立即停止旋转。

注意,如果流为空,那么 now_or_never 成功,因为 next() 立即 returns None案例.