pub struct EventBus<T: Clone + Send + Sync + 'static> { /* private fields */ }
Expand description
Manages a generic, multi-producer, single-consumer (MPSC), thread-safe event channel.
This EventBus
is generic over the event type T
it transports. It serves as a
foundational communication primitive within Khora, allowing different parts of the
engine to communicate in a decoupled manner.
The design is intentional: there are many senders but only one receiver, ensuring that a single, authoritative system is responsible for processing all events of a given type. Senders can be cloned freely and passed to different threads.
§Examples
#[derive(Clone, Debug, PartialEq)]
enum GameEvent {
PlayerJumped,
ScoreChanged(u32),
}
// Create a new bus for our specific event type.
let event_bus = EventBus::<GameEvent>::new();
// Clone the sender to give to a game system.
let sender = event_bus.sender();
// A system publishes an event.
sender.send(GameEvent::PlayerJumped);
// The main event loop (the owner of the bus) processes the event.
if let Ok(event) = event_bus.receiver().try_recv() {
assert_eq!(event, GameEvent::PlayerJumped);
}
Implementations§
Source§impl<T: Clone + Send + Sync + 'static> EventBus<T>
impl<T: Clone + Send + Sync + 'static> EventBus<T>
Sourcepub fn publish(&self, event: T)
pub fn publish(&self, event: T)
Publishes an event to all receivers.
This method is a convenience wrapper around the channel’s send
operation.
It logs an error if the send fails, which typically means the receiver
(and thus the EventBus
instance) has been dropped.
§Arguments
event
: The event of typeT
to be sent over the channel.