48 lines
1.5 KiB
Rust
48 lines
1.5 KiB
Rust
use std::future::Future;
|
|
|
|
/// Handler trait for asynchronous event callbacks.
|
|
///
|
|
/// This trait is automatically implemented for any closure matching
|
|
/// `Fn(E) -> Future<Output = ()> + Send + Sync + 'static`.
|
|
///
|
|
/// By using `Fn(E) -> <Self as AsyncHandler<E>>::Fut` as a supertrait,
|
|
/// Rust propagates the event type `E` directly into the closure's parameter,
|
|
/// enabling seamless turbofish syntax with clean field access:
|
|
///
|
|
/// ```rust,no_run
|
|
/// # use event_bus::EventBus;
|
|
/// # #[derive(Clone)] struct MessageUpdatedEvent { id: u64 }
|
|
/// # let bus = EventBus::new();
|
|
/// bus.on_async::<MessageUpdatedEvent>(|event| async move {
|
|
/// println!("Updated: {:?}", event.id);
|
|
/// });
|
|
/// ```
|
|
pub trait AsyncHandler<E>: Fn(E) -> <Self as AsyncHandler<E>>::Fut + Send + Sync + 'static {
|
|
type Fut: Future<Output = ()> + Send + 'static;
|
|
}
|
|
|
|
impl<E, F, Fut> AsyncHandler<E> for F
|
|
where
|
|
F: Fn(E) -> Fut + Send + Sync + 'static,
|
|
Fut: Future<Output = ()> + Send + 'static,
|
|
{
|
|
type Fut = Fut;
|
|
}
|
|
|
|
/// Handler trait for asynchronous event callbacks with an injected context.
|
|
///
|
|
/// Automatically implemented for closures matching
|
|
/// `Fn(C, E) -> Future<Output = ()> + Send + Sync + 'static`.
|
|
pub trait AsyncHandlerWith<E, C>: Fn(C, E) -> <Self as AsyncHandlerWith<E, C>>::Fut + Send + Sync + 'static {
|
|
type Fut: Future<Output = ()> + Send + 'static;
|
|
}
|
|
|
|
impl<E, C, F, Fut> AsyncHandlerWith<E, C> for F
|
|
where
|
|
C: Clone + Send + Sync + 'static,
|
|
F: Fn(C, E) -> Fut + Send + Sync + 'static,
|
|
Fut: Future<Output = ()> + Send + 'static,
|
|
{
|
|
type Fut = Fut;
|
|
}
|