Skip to main content

EventEmitter

Trait EventEmitter 

Source
pub trait EventEmitter<E: Any>: 'static { }
Expand description

Declares that an entity type emits events of type E.

Implement it with an empty impl. Then emit events with Context::emit, and receive them with Context::subscribe.

§Examples

use gpui::{AppContext, Context, EventEmitter, TestApp};

struct Counter {
    count: usize,
}

struct Incremented(usize);

impl EventEmitter<Incremented> for Counter {}

impl Counter {
    fn add(&mut self, amount: usize, cx: &mut Context<Self>) {
        self.count += amount;
        cx.emit(Incremented(amount));
        cx.notify();
    }
}

let mut app = TestApp::new();
let (counter, total, _subscription) = app.update(|cx| {
    let counter = cx.new(|_| Counter { count: 0 });
    let total = cx.new(|_| 0_usize);
    let total_for_subscriber = total.clone();
    let subscription = cx.subscribe(&counter, move |_, event: &Incremented, cx| {
        total_for_subscriber.update(cx, |total, _| *total += event.0);
    });
    (counter, total, subscription)
});
app.update(|cx| counter.update(cx, |counter, cx| counter.add(2, cx)));
app.read(|cx| assert_eq!(*total.read(cx), 2));

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§