Skip to content

Instantly share code, notes, and snippets.

@mike-pete
Last active January 26, 2024 05:12
Show Gist options
  • Save mike-pete/2b8ad38f2c9680b6ee84ef00dc50d404 to your computer and use it in GitHub Desktop.
Save mike-pete/2b8ad38f2c9680b6ee84ef00dc50d404 to your computer and use it in GitHub Desktop.
Pub/Sub
const pubSub = <UpdateType>() => {
type Subscriber = ({ update, unsubscribe }: { update: UpdateType; unsubscribe: () => void }) => void
const subscribers = new Set<Subscriber>()
const subscribe = (sub: Subscriber) => subscribers.add(sub)
const publish = (update: UpdateType) => {
subscribers.forEach((sub) => {
const unsubscribe = () => subscribers.delete(sub)
sub({ update, unsubscribe })
})
}
return {
subscribe,
publish,
}
}
const updateHandler = ({ update, unsubscribe }: { update: string; unsubscribe: () => void }) => {
console.log('update:', update)
if (update === 'update 2') {
unsubscribe()
}
}
const { subscribe, publish } = pubSub<string>()
publish('update 0') // no subscribers yet
subscribe(updateHandler)
publish('update 1') // update: update 1
publish('update 2') // update: update 2
publish('update 3') // no subscribers left
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment