Skip to main content

EventStream

Struct EventStream 

Source
pub struct EventStream<T> { /* private fields */ }
Expand description

A stream of discrete events. It has no current value.

Implementations§

Source§

impl<T> EventStream<T>
where T: 'static,

Source

pub fn debounce(&self, timer: Rc<dyn Timer>, window: Duration) -> EventStream<T>

Emit only after the stream has been quiet for window.

Each event restarts the window; when it elapses without a newer event, the latest event is emitted. Superseded timer firings are no-ops.

Source

pub fn throttle(&self, timer: Rc<dyn Timer>, window: Duration) -> EventStream<T>

Emit at most one event per window: the first event immediately (leading edge) and the last event of the window when it elapses (trailing edge).

Source

pub fn delay(&self, timer: Rc<dyn Timer>, window: Duration) -> EventStream<T>

Emit every event in order, each at least window after it arrived.

Source§

impl<T> EventStream<T>
where T: 'static,

Source

pub fn observe<F>(&self, f: F) -> Subscription
where F: FnMut(&T) + 'static,

Observe this stream. The callback fires for every event while the returned Subscription is alive. Streams are started by their first observer and stopped when the last observer is removed.

Examples found in repository?
examples/bench_large_table.rs (line 23)
14fn main() {
15    const ROWS: usize = 100_000;
16    const UPDATES: usize = 10_000;
17
18    let model = ListModel::new();
19    let events = Rc::new(Cell::new(0usize));
20    let events_rc = events.clone();
21    let _sub = model
22        .changes()
23        .observe(move |_| events_rc.set(events_rc.get() + 1));
24
25    let rows: Vec<String> = (0..ROWS).map(|i| format!("row-{i:05}")).collect();
26
27    let started = Instant::now();
28    model.replace_all(rows);
29    let load = started.elapsed();
30
31    let started = Instant::now();
32    for i in 0..UPDATES {
33        model.set(i % ROWS, format!("updated-{i:05}"));
34    }
35    let updates = started.elapsed();
36
37    let started = Instant::now();
38    model.sort_by(|a, b| a.cmp(b));
39    let sort = started.elapsed();
40
41    println!(
42        "rows={ROWS} updates={UPDATES} change-events={} ({} Reset + {UPDATES} Update, no rebuilds)\n\
43         load={load:?}  {UPDATES} per-row updates={updates:?}  sort={sort:?}",
44        events.get(),
45        events.get() - UPDATES
46    );
47}
More examples
Hide additional examples
examples/validation.rs (lines 39-41)
11fn main() {
12    // Counter state.
13    let count = Var::new(0);
14
15    // Derived state: a doubled value and a validation message.
16    let doubled = count.signal().map(|c| c * 2);
17    let validation = count.signal().map(|c| {
18        if *c < 0 {
19            "negative"
20        } else if *c > 10 {
21            "too large"
22        } else {
23            "ok"
24        }
25    });
26
27    // Event sampling: what was the count when a "click" happened?
28    let clicks = Sink::new();
29    let clicked_value = clicks.stream().sample(&count.signal());
30
31    let log: Rc<RefCell<Vec<(i32, &str)>>> = Rc::new(RefCell::new(Vec::new()));
32    let log_rc = log.clone();
33    let count_rc = count.clone();
34    let validation_rc = validation.clone();
35    let _count_sub = count_rc.signal().observe(move |value| {
36        log_rc.borrow_mut().push((*value, *validation_rc.value()));
37    });
38    let log_rc = log.clone();
39    let _clicked_sub = clicked_value.observe(move |value| {
40        log_rc.borrow_mut().push((*value, "sampled"));
41    });
42
43    count.set(5);
44    clicks.send(());
45    count.set(12);
46
47    assert_eq!(*doubled.value(), 24);
48    assert_eq!(*validation.value(), "too large");
49    assert_eq!(
50        *log.borrow(),
51        vec![(0, "ok"), (5, "ok"), (5, "sampled"), (12, "too large")]
52    );
53    println!(
54        "counter={} doubled={} validation={}",
55        count.value(),
56        doubled.value(),
57        validation.value()
58    );
59}
Source

pub fn observe_with(&self, observer: &Observer<T>) -> Subscription

Observe this stream with a shared Observer.

Source

pub fn map<U, F>(&self, f: F) -> EventStream<U>
where U: 'static, F: FnMut(&T) -> U + 'static,

Map every event.

Source

pub fn filter<F>(&self, f: F) -> EventStream<T>
where F: FnMut(&T) -> bool + 'static,

Keep only events that satisfy the predicate.

Source

pub fn filter_map<U, F>(&self, f: F) -> EventStream<U>
where U: 'static, F: FnMut(&T) -> Option<U> + 'static,

Map and filter in one step.

Source

pub fn fold<U, F>(&self, init: U, f: F) -> EventStream<U>
where U: 'static, F: FnMut(&U, &T) -> U + 'static,

Emit the running fold of every event.

Source

pub fn distinct(&self) -> EventStream<T>
where T: PartialEq,

Drop consecutive duplicates.

Source

pub fn merge(&self, other: &EventStream<T>) -> EventStream<T>

Merge events from two streams, preserving arrival order.

Source

pub fn merge_all(streams: Vec<EventStream<T>>) -> EventStream<T>

Merge events from many streams, preserving arrival order.

Source

pub fn sample<S>(&self, signal: &Signal<S>) -> EventStream<S>
where S: 'static,

Emit the sampled signal’s current value whenever this stream fires.

Examples found in repository?
examples/validation.rs (line 29)
11fn main() {
12    // Counter state.
13    let count = Var::new(0);
14
15    // Derived state: a doubled value and a validation message.
16    let doubled = count.signal().map(|c| c * 2);
17    let validation = count.signal().map(|c| {
18        if *c < 0 {
19            "negative"
20        } else if *c > 10 {
21            "too large"
22        } else {
23            "ok"
24        }
25    });
26
27    // Event sampling: what was the count when a "click" happened?
28    let clicks = Sink::new();
29    let clicked_value = clicks.stream().sample(&count.signal());
30
31    let log: Rc<RefCell<Vec<(i32, &str)>>> = Rc::new(RefCell::new(Vec::new()));
32    let log_rc = log.clone();
33    let count_rc = count.clone();
34    let validation_rc = validation.clone();
35    let _count_sub = count_rc.signal().observe(move |value| {
36        log_rc.borrow_mut().push((*value, *validation_rc.value()));
37    });
38    let log_rc = log.clone();
39    let _clicked_sub = clicked_value.observe(move |value| {
40        log_rc.borrow_mut().push((*value, "sampled"));
41    });
42
43    count.set(5);
44    clicks.send(());
45    count.set(12);
46
47    assert_eq!(*doubled.value(), 24);
48    assert_eq!(*validation.value(), "too large");
49    assert_eq!(
50        *log.borrow(),
51        vec![(0, "ok"), (5, "ok"), (5, "sampled"), (12, "too large")]
52    );
53    println!(
54        "counter={} doubled={} validation={}",
55        count.value(),
56        doubled.value(),
57        validation.value()
58    );
59}
Source

pub fn start_with(&self, initial: T) -> Signal<T>
where T: PartialEq,

Turn this stream into a signal that starts with initial and holds the latest event.

Source

pub fn flat_map_switch<U, F>(&self, f: F) -> EventStream<U>
where U: 'static, F: FnMut(&T) -> EventStream<U> + 'static,

Switch to the latest inner stream produced by f; only the current inner stream’s events are emitted.

Trait Implementations§

Source§

impl<T: 'static> Clone for EventStream<T>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl<T> !RefUnwindSafe for EventStream<T>

§

impl<T> !Send for EventStream<T>

§

impl<T> !Sync for EventStream<T>

§

impl<T> !UnwindSafe for EventStream<T>

§

impl<T> Freeze for EventStream<T>
where PhantomData<T>: Freeze,

§

impl<T> Unpin for EventStream<T>
where PhantomData<T>: Unpin,

§

impl<T> UnsafeUnpin for EventStream<T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.