Last active
July 19, 2024 11:39
-
-
Save SiddharthaChowdhury/202f898dabb4bd8db7d283baeb69c8f8 to your computer and use it in GitHub Desktop.
Example Pub-Sub class typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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