2 个版本
0.1.1 | 2024年4月15日 |
---|---|
0.1.0 | 2024年4月15日 |
#1008 in 异步
16KB
211 行
Hash Events
一个支持自定义事件的 MPMC 事件系统。事件以有效载荷的形式发出,该事件的订阅者是一个有效载荷流。对于每个事件,都会触发所有订阅者。
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));
依赖关系
~1MB
~19K SLoC