Function sample

Source
pub fn sample<O>(s: RS2Stream<O>, interval: Duration) -> RS2Stream<O>
where O: Clone + Send + 'static,
Expand description

Sample a rs2_stream at regular intervals, emitting the most recent value

This combinator samples the most recent value from a rs2_stream at a regular interval. It only emits a value if at least one new value has arrived since the last emission. If no new value has arrived during an interval, that interval is skipped.

ยงExamples

use rs2_stream::rs2::*;
use futures_util::stream::StreamExt;
use std::time::Duration;
use tokio::time::sleep;
use async_stream::stream;

// Create a rs2_stream that emits values faster than the sample interval
let rs2_stream = stream! {
    yield 1;
    sleep(Duration::from_millis(10)).await;
    yield 2;
    sleep(Duration::from_millis(10)).await;
    yield 3;
    sleep(Duration::from_millis(100)).await;
    yield 4;
};

// Sample the rs2_stream every 50ms
let result = sample(rs2_stream.boxed(), Duration::from_millis(50))
    .collect::<Vec<_>>()
    .await;

// We expect to get the most recent value at each interval:
// - 3 (the most recent value after the first 50ms)
// - 4 (the most recent value after the next 50ms)
assert_eq!(result, vec![3, 4]);