pub trait StreamBuffer<T> {
type Item;
// Required methods
fn push(&mut self, item: T) -> Option<T>;
fn pop(&mut self) -> Option<Self::Item>;
}Expand description
Decides what into_stream_with keeps
when the source pushes faster than the stream is polled.
An observable pushes at its own pace while a Stream hands out one item per poll, so the
items that arrive between two polls have to go somewhere. The buffer is where: every item
the source pushes goes through push, and every poll takes the next item out
with pop. A Stream cannot slow its source down, so the buffer alone
decides what survives — and at what cost in memory — when the consumer falls behind.
Three buffers come with the crate: Unbounded keeps everything, Latest keeps the
newest item only, and Bounded keeps a fixed number of items and drops the oldest or the
newest beyond that. An implementation of your own can also fold the items that pile up into
one, which is why the item the stream yields (Item) need not be the item
the source pushes.
§Examples
A buffer that adds up the numbers that arrive between two polls:
use futures::{FutureExt, StreamExt};
use rx_rust::{
observable::ObservableExt, observer::Observer,
operators::others::observable_try_stream::StreamBuffer,
subject::publish_subject::PublishSubject,
};
use std::convert::Infallible;
#[derive(Default)]
struct Sum(Option<i32>);
impl StreamBuffer<i32> for Sum {
type Item = i32;
fn push(&mut self, item: i32) -> Option<i32> {
*self.0.get_or_insert(0) += item;
None
}
fn pop(&mut self) -> Option<i32> {
self.0.take()
}
}
let mut subject = PublishSubject::<_, Infallible>::new();
let mut stream = subject.clone().into_stream_with(Sum::default());
assert_eq!(stream.next().now_or_never(), None); // subscribes
subject.on_next(1);
subject.on_next(2);
subject.on_next(3);
assert_eq!(stream.next().now_or_never(), Some(Some(6)));Required Associated Types§
Required Methods§
Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".