2 releases
0.1.1 | Apr 15, 2024 |
---|---|
0.1.0 | Apr 15, 2024 |
#1634 in Asynchronous
16KB
211 lines
Hash Events
An MPMC event system that allows for custom events. Events are emitted with a payload, and subscribers to that event are stream of payloads. For each event, all subscribers are triggered.
use hash_events::EventManager;
use futures_lite::StreamExt;
use futures::executor::block_on;
// First, create an `EventManager` using a custom event, or the built-in `StringEvent`.
#[derive(Debug, PartialEq, Eq, Hash)]
struct SimpleEvent(String);
let mut manager: EventManager<SimpleEvent, i32> = EventManager::new();
// Then subscribe to an event. You can listen for all events, or just one. Subscriber streams can be cloned.
let mut subscriber = manager.subscribe(SimpleEvent("Event".into()));
let mut subscriber_once = manager.once(SimpleEvent("Event2".into()));
let mut subscriber2 = subscriber.clone();
// Then events can be emitted from the event manger or an event emitter.
manager.emit(SimpleEvent("Event".into()), 57);
let mut emitter = manager.emitter(SimpleEvent("Event2".into()));
emitter.emit(56);
// The subscribers will receive payloads for matching events.
assert_eq!(block_on(subscriber.next()), Some(57));
assert_eq!(block_on(subscriber2.next()), Some(57));
assert_eq!(block_on(subscriber_once), Ok(56));
Dependencies
~1MB
~19K SLoC