Review this generated single-threaded event bus against the stated contract.
Keep subscriber names unique, let callbacks subscribe safely, apply changes on the next publication, clone only cheap handles for a snapshot, and produce no output.
Rust
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Clone)]
struct Handler {
name: String,
run: Rc<dyn Fn(&Bus)>,
}
struct Bus { handlers: RefCell<Vec<Handler>> }
impl Bus {
fn subscribe(&self, handler: Handler) -> bool {
self.handlers.borrow_mut().push(handler);
true
}
fn publish(&self) {
let snapshot = self.handlers.borrow().clone();
let _exclusive = self.handlers.borrow_mut();
for handler in snapshot {
(handler.run)(self);
}
println!("published");
}
}
generated code is illustrative, not from any one model