Skip to content

Instantly share code, notes, and snippets.

@sidola
Last active May 14, 2022 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidola/eaf987d8c4c7e8445b61dc07c33a842f to your computer and use it in GitHub Desktop.
Save sidola/eaf987d8c4c7e8445b61dc07c33a842f to your computer and use it in GitHub Desktop.
Experimental PubSub impl. as a class
class PubSub<T> {
private handlers: { [key: string]: any[] } = {}
public subscribe<E extends keyof T & string>(
event: E,
callback: (message: T[E]) => void
) {
const list = this.handlers[event] ?? []
list.push(callback)
this.handlers[event] = list
return callback
}
public unsubscribe<E extends keyof T & string>(
event: E,
callback: (message: T[E]) => void
) {
let list = this.handlers[event] ?? []
list = list.filter(h => h !== callback)
this.handlers[event] = list
}
public publish<E extends keyof T & string>(
event: E,
message: T[E]
) {
this.handlers[event].forEach(h => h(message))
}
}
type Events = {
warn: { errorCode: number, userMessage: string },
error: { shitThatWentWrong: string },
}
const pubSub = new PubSub<Events>()
const subHandler = pubSub.subscribe("error", (message) => {
console.log(message.shitThatWentWrong)
})
pubSub.publish("error", { shitThatWentWrong: "boom" })
// Allowed, correct handler type
pubSub.unsubscribe('error', subHandler)
// Not allowed, incorrect handler type
pubSub.unsubscribe('warn', subHandler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment