Dead simple Rust event system.
src | ||
.envrc | ||
.gitignore | ||
Cargo.lock | ||
Cargo.toml | ||
flake.lock | ||
flake.nix | ||
LICENSE | ||
README.md |
Simple Events
Simple Events is a dead simple event library for Rust, providing functionality to register static functions or closures as event handlers, as well as to dispatch almost any kind of struct as an event to be handled by registered handlers either sequentially or in parallel.
Examples
Static Functions
use simple_events::*;
// An event struct can be almost anything that implements `Copy`
#[derive(Debug)]
struct Dummy;
// A handler function must take in exactly 1 argument of type `Event<T>`.
// The event passed to this function is a copy.
fn handler_fn(event: Event<Dummy>) {
// Do something with the event here
}
fn main() {
// This automatically registers `handler_fn` to handle any `Event<Dummy>` that
// are dispatched in the future.
add_event_handler(handler_fn);
// Dispatches an event of type `Event<Dummy>`, calling `handler_fn`
dispatch(Dummy);
// Function event handlers can be removed as such:
remove_event_handler(handler_fn);
}
Closures
use simple_events::*;
#[derive(Debug)]
struct Dummy;
fn main() {
let closure = |event: Event<Dummy>| { /* Do something with the event here */ };
// This automatically registers `closure` to handle any `Event<Dummy>` that
// are dispatched in the future.
//
// `add_event_handler` returns a reference that can later be used to remove
// the event handler the ref belongs to.
let handler_ref = add_event_handler(closure);
// Dispatches an event of type `Event<Dummy>`, calling `closure`
dispatch(Dummy);
// Closure event handlers can be removed as such:
remove_event_handler(handler_ref);
}
Notes
dispatch
calls every registered event handler sequentially, so they should not take too long to execute in order to avoid blocking the thread for too long.dispatch_parallel
exists as an alternative fordispatch
, which spawns a separate thread for each registered event handler, and returns once all event handlers have finished executing.- Although event handler calls in
dispatch
are sequential, execution order is not guaranteed onceremvove_event_handler
has been called, since it usesalloc:vec::Vec::swap_remove
behind the scenes.