async-event-emitter
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
- Emitted values should implement an extra trait (Debug) in addition to Serde's Serialize and Deserialize.
- This is an async implementation, currently limited to tokio, but async-std will be added soon under a feature flag.
- 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
Getting Started
use AsyncEventEmitter;
async
Basic Usage
We can emit and listen to values of any type so long as they implement the Debug trait and serde's Serialize and Deserialize traits. A single EventEmitter instance can have listeners to values of multiple types.
use AsyncEventEmitter as EventEmitter;
use ;
async
Removing listeners is also easy
use AsyncEventEmitter as EventEmitter;
let mut event_emitter = new;
let listener_id = event_emitter.on;
match event_emitter.remove_listener
Creating a Global EventEmitter
You'll likely 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;
use Mutex;
use AsyncEventEmitter;
// Use lazy_static! because the size of EventEmitter is not known at compile time
lazy_static! .
async
async
License
MIT License (MIT), see LICENSE