| 26 | type Listener<T> = (payload: T) => void; |
| 27 | |
| 28 | function createEventHub<T>(eventName: string) { |
| 29 | const listeners = new Set<Listener<T>>(); |
| 30 | let unlisten: Unsubscribe | null = null; |
| 31 | let listenPromise: Promise<Unsubscribe> | null = null; |
| 32 | |
| 33 | const start = (options?: SubscriptionOptions) => { |
| 34 | if (unlisten || listenPromise) { |
| 35 | return; |
| 36 | } |
| 37 | listenPromise = listen<T>(eventName, (event) => { |
| 38 | for (const listener of listeners) { |
| 39 | try { |
| 40 | listener(event.payload); |
| 41 | } catch (error) { |
| 42 | console.error(`[events] ${eventName} listener failed`, error); |
| 43 | } |
| 44 | } |
| 45 | }); |
| 46 | listenPromise |
| 47 | .then((handler) => { |
| 48 | listenPromise = null; |
| 49 | if (listeners.size === 0) { |
| 50 | handler(); |
| 51 | return; |
| 52 | } |
| 53 | unlisten = handler; |
| 54 | }) |
| 55 | .catch((error) => { |
| 56 | listenPromise = null; |
| 57 | options?.onError?.(error); |
| 58 | }); |
| 59 | }; |
| 60 | |
| 61 | const stop = () => { |
| 62 | if (unlisten) { |
| 63 | try { |
| 64 | unlisten(); |
| 65 | } catch { |
| 66 | // Ignore double-unlisten when tearing down. |
| 67 | } |
| 68 | unlisten = null; |
| 69 | } |
| 70 | }; |
| 71 | |
| 72 | const subscribe = ( |
| 73 | onEvent: Listener<T>, |
| 74 | options?: SubscriptionOptions, |
| 75 | ): Unsubscribe => { |
| 76 | listeners.add(onEvent); |
| 77 | start(options); |
| 78 | return () => { |
| 79 | listeners.delete(onEvent); |
| 80 | if (listeners.size === 0) { |
| 81 | stop(); |
| 82 | } |
| 83 | }; |
| 84 | }; |
| 85 | |