async_events_emitter/event_emitter.rs
1use std::{
2 any::{Any, TypeId},
3 collections::HashMap,
4 sync::{
5 atomic::{AtomicUsize, Ordering},
6 Arc,
7 },
8};
9
10use dashmap::DashMap;
11
12use crate::{
13 event::EventHandler,
14 listener::{Listener, ListenerId},
15 Event,
16};
17
18type EventsMap = Arc<DashMap<TypeId, HashMap<ListenerId, Box<dyn Any + Send + Sync>>>>;
19
20/// The [`EventEmitter`] struct is the core of the event handling system.
21/// It allows registration of event handlers and emits events to these handlers.
22///
23/// # Examples
24/// ```no_compile
25/// use async_events_emitter::{EventEmitter, Event, EventHandler};
26/// use async_trait::async_trait;
27///
28/// #[derive(Debug, Clone)]
29/// pub struct MyCustomEvent;
30///
31/// #[derive(Debug, Clone)]
32/// pub struct MyEventHandler;
33///
34/// impl Event for MyCustomEvent {};
35///
36/// #[async_trait]
37/// impl EventHandler<MyCustomEvent> for MyEventHandler {
38/// async fn handle_event(&mut self, event: MyCustomEvent) {
39/// // Handle event data here..
40/// println!("{:?}", event)
41/// }
42/// }
43///
44/// // Create a new EventEmitter
45/// let mut event_emitter = EventEmitter::new();
46/// let my_event_handler = MyEventHandler;
47///
48/// // Register event handlers
49/// event_emitter.on::<MyCustomEvent>(my_event_handler);
50///
51/// // Emit an event
52/// event_emitter.emit(MyCustomEvent);
53/// ```
54pub struct EventEmitter {
55 events: EventsMap,
56 next_id: AtomicUsize,
57}
58
59impl Default for EventEmitter {
60 fn default() -> Self {
61 Self::new()
62 }
63}
64
65impl EventEmitter {
66 /// Creates a new instance of the `EventEmitter`.
67 ///
68 /// This function initializes the `EventEmitter` with empty event handlers. It's ideal for
69 /// starting an event-driven application where you'll be adding handlers dynamically.
70 pub fn new() -> Self {
71 Self {
72 events: Arc::new(DashMap::new()),
73 next_id: AtomicUsize::new(0),
74 }
75 }
76
77 /// Creates a new instance of the `EventEmitter` with a specified capacity.
78 ///
79 /// This variant of the constructor allows you to specify an initial capacity for event listeners,
80 /// which can be useful for performance optimization in scenarios where a large number of listeners
81 /// are expected.
82 ///
83 /// # Arguments
84 /// * `capacity`: The initial capacity for storing event listeners.
85 ///
86 /// # Examples
87 /// ```
88 /// let mut event_emitter = EventEmitter::with_capacity(100);
89 /// ```
90 pub fn with_capacity(capacity: usize) -> Self {
91 Self {
92 events: Arc::new(DashMap::with_capacity(capacity)),
93 next_id: AtomicUsize::new(0),
94 }
95 }
96 /// Registers a handler for a specific event type.
97 ///
98 /// The on method allows you to register a handler that will be called every time an event of a specific type is emitted. This is useful for setting up listeners that should persist and handle all occurrences of an event.
99 /// # Type Parameters
100 /// * E: The type of the event to listen for. This type must implement the Event trait.
101 ///
102 /// # Arguments
103 /// * handler: An implementation of the EventHandler<E> trait. This handler will be called for every emitted event of type E.
104 ///
105 /// # Returns
106 /// Returns a ListenerId which can be used to remove the listener at a later time with the off method.
107 ///
108 /// # Examples
109 /// ```
110 /// use async_events_emitter::*;
111 ///
112 /// #[derive(Debug, Clone)]
113 /// struct MyCustomEvent;
114 ///
115 /// let mut event_emitter = EventEmitter::new();
116 /// event_emitter.on::<MyCustomEvent>(my_event_handler);
117 /// ```
118 pub fn on<E: Event + 'static>(
119 &mut self,
120 handler: impl EventHandler<E> + 'static,
121 ) -> ListenerId {
122 self.add_listener(handler, false)
123 }
124
125 /// Registers a handler for a specific event type, but only for the next occurrence.
126 ///
127 /// This method is similar to on, but the handler will be automatically unregistered after it handles an event once.
128 ///
129 /// # Type Parameters
130 /// * E: The type of the event to listen for.
131 ///
132 /// # Arguments
133 /// * handler: The handler for the event, which will be called only once.
134 ///
135 /// # Returns
136 /// Returns a ListenerId, which can be used to prematurely remove the listener if needed.
137 ///
138 /// # Examples
139 /// ```
140 /// use async_events_emitter::*;
141 ///
142 /// #[derive(Debug, Clone)]
143 /// struct MyCustomEvent;
144 ///
145 /// let mut event_emitter = EventEmitter::new();
146 /// event_emitter.once::<MyCustomEvent>(my_event_handler);
147 /// ```
148 pub fn once<E: Event + 'static>(
149 &mut self,
150 handler: impl EventHandler<E> + 'static,
151 ) -> ListenerId {
152 self.add_listener(handler, true)
153 }
154
155 /// Emits an event, triggering all registered handlers for its type.
156 ///
157 /// This method is used to emit an event of type E, which will be handled by all the registered handlers for this type.
158 ///
159 /// # Type Parameters
160 /// * E: The type of the event being emitted. Must implement Event and Clone and be Send and 'static.
161 ///
162 /// # Arguments
163 /// * event: The event instance to emit.
164 pub fn emit<E: Event + 'static>(&self, event: E)
165 where
166 E: Clone + Send + 'static, // Ensure E is Clone and Send
167 {
168 let listeners = {
169 self.events
170 .get(&TypeId::of::<E>())
171 .map(|listeners_for_type| {
172 listeners_for_type
173 .iter()
174 .filter_map(|(_, listener)| listener.downcast_ref::<Listener<E>>())
175 .cloned() // Clone each listener
176 .collect::<Vec<_>>() // Collect into a Vec
177 })
178 };
179 let mut to_remove = Vec::new();
180
181 if let Some(ref listeners) = listeners {
182 for listener in listeners.clone() {
183 let event_clone = event.clone(); // Clone event for each listener
184 if listener.once {
185 to_remove.push(listener.id.clone());
186 }
187 tokio::spawn(async move {
188 listener.call(&event_clone).await
189 // if let Err(e) = {
190 // eprintln!("Error handling event: {:?}", e);
191 // }
192 });
193 }
194 }
195 drop(listeners); // Important: Release the lock before modifying the collection
196
197 // Remove 'once' listeners
198 if !to_remove.is_empty() {
199 if let Some(mut listeners_for_type) = self.events.get_mut(&TypeId::of::<E>()) {
200 for id in to_remove {
201 listeners_for_type.remove(&id);
202 }
203 }
204 }
205
206 }
207
208 /// An alias for [`EventEmitter::remove_listener()`] Removes a specific listener based on its ListenerId.
209 ///
210 /// This method is used to unsubscribe a previously registered event handler. The handler will no longer receive event notifications.
211 ///
212 /// # Arguments
213 /// * listener_id: The ListenerId of the handler to be removed. This ID is obtained when registering a handler using on or once.
214 pub fn off<E: Event + 'static>(&mut self, listener_id: ListenerId) where E: Clone + Send + 'static {
215 self.remove_listener(listener_id)
216 }
217
218 /// Removes a listener from the internal events map based on its ListenerId.
219 ///
220 /// This internal method provides the core functionality for unregistering an event handler. It is used by the public off method.
221 ///
222 /// # Arguments
223 /// * listener_id: The ListenerId of the listener to be removed.
224 pub fn remove_listener(&self, listener_id: ListenerId) {
225 if let Some(mut listeners_for_type) = self.events.get_mut(&listener_id.type_id) {
226 listeners_for_type.remove(&listener_id);
227 }
228 }
229
230 /// Retrieves all listeners for a specific event type.
231 ///
232 /// This method returns a list of all registered listeners for a given event type E. It's useful for debugging or introspection purposes.
233 ///
234 /// # Type Parameters
235 /// * E: The type of the event.
236 ///
237 /// # Returns
238 /// Returns an Option<Vec<Listener<E>>> containing all listeners for the event type E. Returns None if there are no listeners for this event type.
239 pub fn get_event_listeners<E: Event + 'static>(&self) -> Option<Vec<Listener<E>>> where E: Clone + Send + 'static {
240 let event_listeners = {
241 self.events.get(&TypeId::of::<E>()).map(|listeners_of_type| {
242 listeners_of_type
243 .iter()
244 .filter_map(|(_, listener)| listener.downcast_ref::<Listener<E>>())
245 .cloned() // Clone each listener
246 .collect::<Vec<_>>() // Collect into a Vec
247 })
248 };
249 event_listeners
250 }
251
252 pub fn listeners_count(&self) -> usize {
253 // let mut count = 0;
254 // for key in self.events.iter().into_iter() {
255
256 // count += self.events.get(&key).unwrap().len();
257 // }
258 todo!();
259 }
260
261 pub fn event_listeners_count<E: Event + 'static>(&self) -> Option<usize>
262 where
263 E: Clone + Send + 'static, // Ensure E is Clone and Send
264 {
265 self.events.get(&TypeId::of::<E>()).map(|listeners| listeners.len())
266 }
267
268 fn add_listener<E: Event + 'static>(&mut self, handler: impl EventHandler<E> + 'static, once: bool) -> ListenerId {
269 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
270
271 let type_id = TypeId::of::<E>();
272 let listener_id = ListenerId { id, type_id };
273 let listener = Listener::new(handler, once, listener_id.clone());
274 self.events
275 .entry(type_id)
276 .or_default()
277 .insert(listener.id.clone(), Box::new(listener));
278 listener_id
279 }
280}