Emit event threaded

This commit is contained in:
2025-11-23 18:01:21 +01:00
parent 538cc8731f
commit 15ff801cb0
2 changed files with 20 additions and 3 deletions
+2 -1
View File
@@ -2,6 +2,7 @@ use std::sync::Arc;
use osui::prelude::*; use osui::prelude::*;
#[derive(Debug, Clone)]
pub struct KeyPress; pub struct KeyPress;
impl Event for KeyPress { impl Event for KeyPress {
@@ -18,7 +19,7 @@ fn main() {
let cx = cx.clone(); let cx = cx.clone();
move || loop { move || loop {
crossterm::event::read().unwrap(); crossterm::event::read().unwrap();
cx.event(&KeyPress); cx.emit_event_threaded(&KeyPress);
} }
}); });
+18 -2
View File
@@ -63,10 +63,26 @@ impl Context {
))); )));
} }
pub fn event<E: Event + 'static>(self: &Arc<Context>, event: &E) { pub fn emit_event<E: Event + 'static>(self: &Arc<Context>, event: &E) {
if let Some(v) = self.event_handlers.lock().unwrap().get(&TypeId::of::<E>()) { if let Some(v) = self.event_handlers.lock().unwrap().get(&TypeId::of::<E>()) {
for i in v { for i in v {
(i.lock().unwrap())(&self.clone(), event); (i.lock().unwrap())(self, event);
}
}
}
pub fn emit_event_threaded<E: Event + Send + Sync + Clone + 'static>(
self: &Arc<Context>,
event: &E,
) {
if let Some(v) = self.event_handlers.lock().unwrap().get(&TypeId::of::<E>()) {
for i in v {
let i = i.clone();
let event = event.clone();
let s = self.clone();
std::thread::spawn(move || {
(i.lock().unwrap())(&s, &event);
});
} }
} }
} }