pub struct EventBus { /* private fields */ }Expand description
A tiny pub/sub event bus
§Performance and Locking
While the event bus is not entirely lock-free, blocking write-locks are only used on registry updates; i.e.
Self::subscribe and Self::shrink_to_fit. Event publication uses a non-blocking read-lock, and event
listening and receiption is completely lock-free. In normal scenarios with moderate subscriber fluctuation, event
passing is largely independent on mutex performance and only affected by the amount of event types and subscribers.
§Memory Allocation and Publication
The event bus itself only (de-)allocates memory on registry updates; i.e. Self::subscribe and
Self::shrink_to_fit.
However, during event publication events are cloned for each subscriber to achieve strong decoupling. If
Clone is not cheap for your event type or you expect a large number of subscribers, consider wrapping the event
into an Arc or similar referencing types to keep the performance and memory impact low.
§Many Subscribers
Due to the type abstraction layer, each new event needs to be checked against every subscriber to see if the subscriber can handle this event. While this check is cheap, it may accumulate if you have a very high event-throughput with lots of subscribers.
Implementations§
Source§impl EventBus
impl EventBus
Sourcepub fn publish<T>(&self, event: T) -> usize
pub fn publish<T>(&self, event: T) -> usize
Publishes an event to all registered subscribers and returns the amount of subscribers addressed
Sourcepub fn subscribe<T>(&self, backlog: usize) -> Subscription<T>
pub fn subscribe<T>(&self, backlog: usize) -> Subscription<T>
Subscribes to a given event type
Sourcepub fn subscribe_where<T, F>(
&self,
backlog: usize,
filter_map: F,
) -> Subscription<T>
pub fn subscribe_where<T, F>( &self, backlog: usize, filter_map: F, ) -> Subscription<T>
Creates an aggregate subscriber for any event type X where aggregate(&X) => Some(T)
§Performance
Please note that the mapping function is called for event for each subscriber to see if the event can be delivered to the subscriber. If the mapping is expensive, it is recommended to add an early-abort check before the real mapping begins to quickly reject invalid types.
§See Also
See also crate::where_into and crate::where_try_into to create mappers for Into and TryInto
convertible types.
Sourcepub fn shrink_to_fit(&self)
pub fn shrink_to_fit(&self)
Shrinks the allocated capacity as much as possible