Типаж Stream
Типаж Stream
похож на Future
, но может давать несколько значений до завершения, а также похож на типаж Iterator
из стандартной библиотеки:
# #![allow(unused_variables)] #fn main() { trait Stream { /// The type of the value yielded by the stream. type Item; /// Attempt to resolve the next item in the stream. /// Retuns `Poll::Pending` if not ready, `Poll::Ready(Some(x))` if a value /// is ready, and `Poll::Ready(None)` if the stream has completed. fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>; } #}
Одним из распространённых примеров Stream
является Receiver
для типа канала из
пакета futures
. Это даёт Some(val)
каждый раз, когда значение отправляется
от Sender
, и даст None
после того, как Sender
был удалён из памяти и все ожидающие сообщения были получены:
# #![allow(unused_variables)] #fn main() { async fn send_recv() { const BUFFER_SIZE: usize = 10; let (mut tx, mut rx) = mpsc::channel::<i32>(BUFFER_SIZE); tx.send(1).await.unwrap(); tx.send(2).await.unwrap(); drop(tx); // `StreamExt::next` is similar to `Iterator::next`, but returns a // type that implements `Future<Output = Option<T>>`. assert_eq!(Some(1), rx.next().await); assert_eq!(Some(2), rx.next().await); assert_eq!(None, rx.next().await); } #}