Pub Sub Channel With Topics

Implement a pub/sub channel with topic subscriptions message filtering and async event delivery for decoupled services.

JavascriptData Fetching

Code

javascriptsnippet
1 line
export function pubSub(){const topics=new Map();function subscribe(topic,handler,filter=()=>true){if(!topics.has(topic))topics.set(topic,new Set());const entry={handler,filter};topics.get(topic).add(entry);return()=>topics.get(topic).delete(entry);}async function publish(topic,message){const subs=topics.get(topic);if(!subs)return;for(const{handler,filter}of[...subs]){if(filter(message))await handler(message);}}function subscriberCount(topic){return topics.get(topic)?.size??0;}return{subscribe,publish,subscriberCount};}

How the snippet works

Pub Sub Channel With Topics reduces to the functions pubSub, subscribe, publish and subscriberCount.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

The result comes back as an object carrying subscribe, publish.

What to watch for

  • The guard !subs short-circuits the flow with an early return when its condition holds.

Applying it

The entry-point signature is export function pubSub()

pubSub is the public entry point; everything else in the file exists to support it.

The call returns subscribe, publish — destructure what you need at the call site.

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `pubSub`, `subscribe`, `publish` at load time.
What does `pubSub` return?
An object carrying `subscribe`, `publish`.