Skip to content

Instantly share code, notes, and snippets.

@SiddharthaChowdhury
Last active July 19, 2024 11:39
Show Gist options
  • Save SiddharthaChowdhury/202f898dabb4bd8db7d283baeb69c8f8 to your computer and use it in GitHub Desktop.
Save SiddharthaChowdhury/202f898dabb4bd8db7d283baeb69c8f8 to your computer and use it in GitHub Desktop.
Example Pub-Sub class typescript
type TEvent = 'player-icu';
type EventCallback<T> = (data: T) => void;
class EventPublisher {
// Subscription Record<EventName, Record<SubscriberId, callback>>
private subscriptions: Record<
string,
Record<string, EventCallback<unknown>>
> = {};
public subscribe<T>(
subscriberId: string,
event: TEvent,
callback: EventCallback<T>
): () => void {
if (!this.subscriptions[event]) {
this.subscriptions[event] = {};
}
this.subscriptions[event][subscriberId] = callback;
// Returning unsubscribe
return () => {
if (this.subscriptions[event]?.[subscriberId]) {
delete this.subscriptions[event][subscriberId];
if (Object.values(this.subscriptions[event]).length === 0) {
delete this.subscriptions[event];
}
}
};
}
public echo<T>(event: TEvent, data: T): void {
if (!this.subscriptions[event]) return;
for (const subscriptionId in this.subscriptions[event]) {
const callback = this.subscriptions[event][subscriptionId];
if (callback) {
callback(data);
}
}
}
}
export { EventPublisher };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment