A simple event bus that can be cloned and shared across threads.
At present the only limitation is the inability to use the same EventBus
inside
on
blocks because it would lead to a deadlock for sync
variants and to an Error
for unsync
variant (thou this is a work in progress).
```rust
enum EventType { Start, Stop, }
enum Status { Stopped, Started, }
let mut bus: EventBus
let status = Rc::new(RefCell::new(Status::Stopped)); let statusclosure = Rc::clone(&status); let statusclosure_2 = Rc::clone(&status);
bus.on(EventType::Start, move || { *statusclosure.borrowmut() = Status::Started; }) .unwrap();
bus.on(EventType::Stop, move || { *statusclosure2.borrow_mut() = Status::Stopped; }) .unwrap();
bus.emit(EventType::Start).expect("Failed to emit");
asserteq!(*status.borrow(), Status::Started); asserteq!(bus.event_count(), 1);
bus.emit(EventType::Stop).expect("Failed to emit");
asserteq!(*status.borrow(), Status::Stopped); asserteq!(bus.event_count(), 2); ```
```rust
let mut bus: EventBus let status = Arc::new(Mutex::new(Status::Stopped));
let final_status = Arc::clone(&status); let t1 = std::thread::spawn(move || {
bus.on(EventType::Start, move || {
let mut statuslock = status.lock().unwrap();
*status_lock = Status::Started;
}).unwrap();
}); let t2 = std::thread::spawn(move || {
bus_clone.emit(EventType::Start).unwrap();
}); t1.join().unwrap();
t2.join().unwrap(); let finalstatuslock = finalstatus.lock().unwrap();
asserteq!(*finalstatuslock, Status::Started)
``` ```rust
let bus: EventBus bus.on(EventType::Start, move |startupdata| {
*statusclosure.borrowmut() = Some(*startupdata.unwrap());
})
.unwrap(); bus.emitwithvalue(EventType::Start, Some(&123)).expect("Failed to emit"); asserteq!(*status.borrow(), Some(123));
asserteq!(bus.event_count(), 1);
```Passing data to events