vertigo/driver_module/
event_emitter.rs

1use crate::{
2    struct_mut::{BTreeMapMut, CounterMut},
3    DropResource,
4};
5use std::rc::Rc;
6
7#[derive(Clone)]
8pub struct EventEmitter<T: Clone + 'static> {
9    counter: Rc<CounterMut>,
10    #[allow(clippy::type_complexity)]
11    list: Rc<BTreeMapMut<u32, Rc<dyn Fn(T) + 'static>>>,
12}
13
14impl<T: Clone + 'static> Default for EventEmitter<T> {
15    fn default() -> Self {
16        EventEmitter {
17            counter: Rc::new(CounterMut::new(1)),
18            list: Rc::new(BTreeMapMut::new()),
19        }
20    }
21}
22
23impl<T: Clone + Send + Sync> EventEmitter<T> {
24    pub fn add<F: Fn(T) + 'static>(&self, callback: F) -> DropResource {
25        let id = self.counter.get_next();
26
27        self.list.insert(id, Rc::new(callback));
28
29        DropResource::new({
30            let list = self.list.clone();
31            move || {
32                list.remove(&id);
33            }
34        })
35    }
36
37    pub fn trigger(&self, value: T) {
38        let callback_list = self
39            .list
40            .map(|state| state.values().cloned().collect::<Vec<_>>());
41
42        for callback in callback_list {
43            callback(value.clone());
44        }
45    }
46}