Last active
January 26, 2024 05:12
-
-
Save mike-pete/2b8ad38f2c9680b6ee84ef00dc50d404 to your computer and use it in GitHub Desktop.
Pub/Sub
This file contains 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
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