Crate async_event_emitter

Source
Expand description

an Async implementation of the event-emitter-rs crate

Allows you to subscribe to events with callbacks and also fire those events. Events are in the form of (strings, value) and callbacks are in the form of closures that take in a value parameter;

§Differences between this crate and event-emitter-rs

  • This is an async implementation that works for all common async runtimes (Tokio, async-std and smol)
  • The listener methods (on and once) take a callback that returns a future instead of a merely a closure.
  • The emit methods executes each callback on each event by spawning a tokio task instead of a std::thread
  • This emitter is thread safe and can also be used lock-free (supports interior mutability).

Note: To use strict return and event types, use typed-emitter, that crate solves this issue too.

§Getting Started

use async_event_emitter::AsyncEventEmitter;
#[tokio::main]
async fn main() {
let event_emitter = AsyncEventEmitter::new();
// This will print <"Hello world!"> whenever the <"Say Hello"> event is emitted
event_emitter.on("Say Hello", |_:()|  async move { println!("Hello world!")});
event_emitter.emit("Say Hello", ()).await;
// >> "Hello world!"

}

§Basic Usage

We can emit and listen to values of any type so long as they implement serde’s Serialize and Deserialize traits. A single EventEmitter instance can have listeners to values of multiple types.

use async_event_emitter::AsyncEventEmitter as EventEmitter;
use serde::{Deserialize, Serialize};
#[tokio::main]
async fn main () {
let event_emitter = EventEmitter::new();
event_emitter.on("Add three", |number: f32| async move  {println!("{}", number + 3.0)});
event_emitter.emit("Add three", 5.0 as f32).await;
event_emitter.emit("Add three", 4.0 as f32).await;

// >> "8.0"
// >> "7.0"

// Using a more advanced value type such as a struct by implementing the serde traits
#[derive(Serialize, Deserialize,Debug)]
struct Date {
    month: String,
    day: String,
}

event_emitter.on("LOG_DATE", |date: Date|  async move {
    println!("Month: {} - Day: {}", date.month, date.day)
});
event_emitter.emit("LOG_DATE", Date {
    month: "January".to_string(),
    day: "Tuesday".to_string()
}).await;
// >> "Month: January - Day: Tuesday"
}

Removing listeners is also easy

use async_event_emitter::AsyncEventEmitter as EventEmitter;
let event_emitter = EventEmitter::new();

let listener_id = event_emitter.on("Hello", |_: ()|  async {println!("Hello World")});
match event_emitter.remove_listener(&listener_id) {
    Some(listener_id) => print!("Removed event listener!"),
    None => print!("No event listener of that id exists")
}

§Creating a Global EventEmitter

It’s likely that you’ll want to have a single EventEmitter instance that can be shared across files;

After all, one of the main points of using an EventEmitter is to avoid passing down a value through several nested functions/types and having a global subscription service.

// global_event_emitter.rs
use lazy_static::lazy_static;
use async_event_emitter::AsyncEventEmitter;

// Use lazy_static! because the size of EventEmitter is not known at compile time
lazy_static! {
    // Export the emitter with `pub` keyword
    pub static ref EVENT_EMITTER: AsyncEventEmitter = AsyncEventEmitter::new();
}

#[tokio::main]
async fn main() {
    EVENT_EMITTER.on("Hello", |_:()|  async {println!("hello there!")});
    EVENT_EMITTER.emit("Hello", ()).await;
}

async fn random_function() {
    // When the <"Hello"> event is emitted in main.rs then print <"Random stuff!">
    EVENT_EMITTER.on("Hello", |_: ()| async { println!("Random stuff!")});
}

§Usage with other runtimes

Check out the examples from the typed version of this crate, just replace the emntter type.

§Testing

Run the tests on this crate with all-features enabled as follows: cargo test --all-features

License: MIT

Structs§

AsyncEventEmitter
AsyncListener

Type Aliases§

AsyncCB