Struct EventDispatcher

Source
pub struct EventDispatcher { /* private fields */ }
Expand description

High-performance event dispatcher

The main component of the Mod Events system. Thread-safe and optimized for high-performance event dispatch with minimal overhead.

§Example

use mod_events::{EventDispatcher, Event};

#[derive(Debug, Clone)]
struct MyEvent {
    message: String,
}

impl Event for MyEvent {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

let dispatcher = EventDispatcher::new();

dispatcher.on(|event: &MyEvent| {
    println!("Received: {}", event.message);
});

dispatcher.emit(MyEvent {
    message: "Hello, World!".to_string(),
});

Implementations§

Source§

impl EventDispatcher

Source

pub fn new() -> Self

Create a new event dispatcher

Source

pub fn subscribe<T, F>(&self, listener: F) -> ListenerId
where T: Event + 'static, F: Fn(&T) -> Result<(), Box<dyn Error + Send + Sync>> + Send + Sync + 'static,

§Example
use mod_events::{EventDispatcher, Event};

#[derive(Debug, Clone)]
struct MyEvent {
    message: String,
}

impl Event for MyEvent {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

let dispatcher = EventDispatcher::new();
dispatcher.subscribe(|event: &MyEvent| {
    // Handle event, can return errors
    if event.message.is_empty() {
        return Err("Message cannot be empty".into());
    }
    println!("Message: {}", event.message);
    Ok(())
});
Source

pub fn subscribe_with_priority<T, F>( &self, listener: F, priority: Priority, ) -> ListenerId
where T: Event + 'static, F: Fn(&T) -> Result<(), Box<dyn Error + Send + Sync>> + Send + Sync + 'static,

Subscribe to an event with a specific priority

Source

pub fn on<T, F>(&self, listener: F) -> ListenerId
where T: Event + 'static, F: Fn(&T) + Send + Sync + 'static,

Subscribe to an event with simple closure (no error handling)

This is the most convenient method for simple event handling.

§Example
use mod_events::{EventDispatcher, Event};

#[derive(Debug, Clone)]
struct MyEvent {
    message: String,
}

impl Event for MyEvent {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

let dispatcher = EventDispatcher::new();
dispatcher.on(|event: &MyEvent| {
    println!("Received: {}", event.message);
});
Source

pub fn subscribe_async<T, F, Fut>(&self, listener: F) -> ListenerId
where T: Event + 'static, F: Fn(&T) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), Box<dyn Error + Send + Sync>>> + Send + 'static,

Subscribe to an async event (requires “async” feature)

Source

pub fn subscribe_async_with_priority<T, F, Fut>( &self, listener: F, priority: Priority, ) -> ListenerId
where T: Event + 'static, F: Fn(&T) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<(), Box<dyn Error + Send + Sync>>> + Send + 'static,

Subscribe to an async event with priority (requires “async” feature)

Source

pub fn dispatch<T: Event>(&self, event: T) -> DispatchResult

Dispatch an event synchronously

Returns a DispatchResult containing information about the dispatch.

§Example
use mod_events::{EventDispatcher, Event};

#[derive(Debug, Clone)]
struct MyEvent {
    message: String,
}

impl Event for MyEvent {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

let dispatcher = EventDispatcher::new();
let result = dispatcher.dispatch(MyEvent {
    message: "Hello".to_string(),
});

if result.all_succeeded() {
    println!("All listeners handled the event successfully");
}
Source

pub async fn dispatch_async<T: Event>(&self, event: T) -> DispatchResult

Dispatch an event asynchronously (requires “async” feature)

Source

pub fn emit<T: Event>(&self, event: T)

Fire and forget - dispatch without waiting for results

This is the most efficient way to dispatch events when you don’t need to check the results.

§Example
use mod_events::{EventDispatcher, Event};

#[derive(Debug, Clone)]
struct MyEvent {
    message: String,
}

impl Event for MyEvent {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

let dispatcher = EventDispatcher::new();
dispatcher.emit(MyEvent {
    message: "Fire and forget".to_string(),
});
Source

pub fn add_middleware<F>(&self, middleware: F)
where F: Fn(&dyn Event) -> bool + Send + Sync + 'static,

Add middleware that can block events

Middleware functions receive events and return true to allow processing or false to block the event.

§Example
use mod_events::{EventDispatcher, Event};

let dispatcher = EventDispatcher::new();
dispatcher.add_middleware(|event: &dyn Event| {
    println!("Processing event: {}", event.event_name());
    true // Allow all events
});
Source

pub fn unsubscribe(&self, listener_id: ListenerId) -> bool

Remove a listener

Returns true if the listener was found and removed, false otherwise.

Source

pub fn listener_count<T: Event + 'static>(&self) -> usize

Get the number of listeners for an event type

Source

pub fn metrics(&self) -> HashMap<TypeId, EventMetadata>

Get event metrics

Source

pub fn clear(&self)

Clear all listeners

Trait Implementations§

Source§

impl Default for EventDispatcher

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Send for EventDispatcher

Source§

impl Sync for EventDispatcher

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.