Expand description
A typed in-process event bus (18.35.0, #93): code that does something publishes an event value; code that cares subscribes to its type.
use std::sync::{Arc, Mutex};
use rust_web_server::events::EventBus;
#[derive(Debug, Clone)]
struct UserSignedUp { email: String }
let bus = EventBus::new();
let welcomed = Arc::new(Mutex::new(Vec::new()));
let w = Arc::clone(&welcomed);
bus.subscribe(move |e: &UserSignedUp| w.lock().unwrap().push(e.email.clone()));
assert_eq!(1, bus.publish(&UserSignedUp { email: "ann@example.com".into() }));
assert_eq!(vec!["ann@example.com"], *welcomed.lock().unwrap());Subscribers run on the publishing thread, in the order they subscribed;
one that panics is skipped (and reported on stderr) without stopping the
others. Slow work belongs in a job the subscriber enqueues. Clones of a
bus share its subscribers. EventBus::forward_to_mcp turns an event
type into MCP notifications, EventBus::forward_to_channel into
channel messages.
Structsยง
- Event
Bus - Subscribers by event type. See the module docs.
- Subscription
Id - What
EventBus::subscribereturns: pass it toEventBus::unsubscribeto stop.