Dead simple Rust event system.
Find a file
2025-03-15 17:37:40 +01:00
src feat: add dispatch_immediate for async api 2025-03-15 17:37:40 +01:00
.envrc init 2025-02-22 13:42:34 +01:00
.gitignore init 2025-02-22 13:42:34 +01:00
Cargo.lock feat: add async api 2025-03-07 10:07:00 +01:00
Cargo.toml feat: split blocking off into its own feature, default to tokio 2025-03-07 22:16:05 +01:00
flake.lock flake: add checks 2025-02-24 20:07:26 +01:00
flake.nix feat: split blocking off into its own feature, default to tokio 2025-03-07 22:16:05 +01:00
LICENSE init 2025-02-22 13:42:34 +01:00
README.md feat: use arc & clone to remove trait bound from T 2025-03-07 11:18:10 +01:00

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 for dispatch, 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 once remvove_event_handler has been called, since it uses alloc:vec::Vec::swap_remove behind the scenes.