I am not sure why it shows the error even if handler will be dropped before call_tracker I tried to play with scope and follow the E0597 instruction but no clue why still errors.
use std::any::Any;
pub trait EventHandler {
fn handle(&self, event: &dyn Any);
}
pub enum EventKey {
ProjectUpdated,
}
pub enum Event {
ProjectUpdated(String),
}
pub struct EventBus {
handlers: Vec<Box<dyn EventHandler>>,
}
impl EventBus {
pub fn new() -> Self {
Self { handlers: Vec::new() }
}
pub fn register(&mut self, key: EventKey, handler: Box<dyn EventHandler>) {
self.handlers.push(handler);
}
pub fn emit(&self, key: EventKey, event: Event) {
for handler in &self.handlers {
handler.handle(&event);
}
}
}
mod tests {
use std::{cell::RefCell, rc::Rc};
use super::*;
struct MyHandler<'a> {
// calls: Rc<RefCell<u8>>,
calls: &'a RefCell<u8>,
}
impl EventHandler for MyHandler<'_> {
fn handle(&self, event: &dyn Any) {
*self.calls.borrow_mut() += 1;
}
}
#[test]
fn can_create_event_bus() {
let call_tracker: RefCell<u8> = RefCell::new(0);
{
let handler = MyHandler { calls: &call_tracker };
{
let mut bus = EventBus::new();
bus.register(EventKey::ProjectUpdated, Box::new(handler));
bus.emit(EventKey::ProjectUpdated, Event::ProjectUpdated("test".to_string()));
}
assert_eq!(*call_tracker.borrow(), 1);
}
}
}