2024-07-03 07:46:31 +00:00
|
|
|
import { chan, Channel, multi } from "@blowater/csp";
|
2023-06-30 14:05:57 +00:00
|
|
|
|
2023-10-04 21:34:43 +00:00
|
|
|
export class EventBus<T> implements EventEmitter<T>, EventSubscriber<T> {
|
2023-06-30 14:05:57 +00:00
|
|
|
private readonly c = chan<T>();
|
|
|
|
private readonly caster = multi<T>(this.c);
|
|
|
|
|
2023-09-06 21:04:25 +00:00
|
|
|
emit = async (event: T) => {
|
2023-06-30 14:05:57 +00:00
|
|
|
await this.c.put(event);
|
2023-09-06 21:04:25 +00:00
|
|
|
};
|
2023-06-30 14:05:57 +00:00
|
|
|
|
|
|
|
onChange() {
|
|
|
|
return this.caster.copy();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export type EventEmitter<T> = {
|
|
|
|
emit: (event: T) => void;
|
|
|
|
};
|
2024-03-15 13:44:17 +00:00
|
|
|
export type emitFunc<T extends { type: string }> = (event: T) => Promise<void>;
|
2023-10-04 21:34:43 +00:00
|
|
|
|
|
|
|
export type EventSubscriber<T> = {
|
|
|
|
onChange(): Channel<T>;
|
|
|
|
};
|