pub trait EventHandler<Ev, Ctx>:
Clone
+ SendOutsideWasm
+ SyncOutsideWasm
+ 'static { }Expand description
Interface for event handlers.
This trait is an abstraction for a certain kind of functions / closures, specifically:
- They must have at least one argument, which is the event itself, a type
that implements
SyncEvent. Any additional arguments need to implement theEventHandlerContexttrait. - Their return type has to be one of:
(), `Result<(), impl Display + Debug- ’static>
(if you are usinganyhow::Resultoreyre::Resultyou can additionally enable theanyhow/eyrefeature to get the verboseDebug` output printed on error)
- ’static>
§How it works
This trait is basically a very constrained version of Fn: It requires at
least one argument, which is represented as its own generic parameter Ev
with the remaining parameter types being represented by the second generic
parameter Ctx; they have to be stuffed into one generic parameter as a
tuple because Rust doesn’t have variadic generics.
Ev and Ctx are generic parameters rather than associated types because
the argument list is a generic parameter for the Fn traits too, so a
single type could implement Fn multiple times with different argument
lists¹. Luckily, when calling Client::add_event_handler with a
closure argument the trait solver takes into account that only a single one
of the implementations applies (even though this could theoretically change
through a dependency upgrade) and uses that rather than raising an ambiguity
error. This is the same trick used by web frameworks like actix-web and
axum.
¹ the only thing stopping such types from existing in stable Rust is that
all manual implementations of the Fn traits require a Nightly feature
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.