Trait matrix_sdk::event_handler::EventHandler[][src]

pub trait EventHandler<Ev, Ctx>: Clone + Send + Sync + '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 the EventHandlerContext trait.
  • Their return type has to be one of: (), Result<(), impl std::error::Error> or anyhow::Result<()> (requires the anyhow Cargo feature to be enabled)

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::register_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

Implementors