BACK
Use casesWebSocket multiplex — channels over one socket
Use cases · 46

WebSocket multiplex — channels over one socket

Pattern

One socket, many logical channels. Messages tagged by topic: chat, notifications, prices. Opening a separate socket per feature is expensive and complex. The fix: routing by topic over one connection.

The problem it solves

An imperative switch(message.topic) in one callback mixes the logic of all features. Every component drags a dependency on the shared socket, and unsubscribing from one channel without affecting others is nontrivial.

Operators and why they matter

  • groupBy(message => message.topic) — splits one message stream into N separate streams by topic.
  • mergeMap(group$ => ...) — subscribe to each group.
  • filter + map — handle a specific channel's messages.

Gotchas

  • groupBy with an unbounded number of topics keeps groups in memory. Use a durationSelector to clean up rare/one-off topics.
  • A simple filter by topic works for 2-3 channels but doesn't scale to dozens. groupBy is cleaner.
  • Don't open a separate socket per feature module. It's not cheap.

What you get

One socket serves several independent feature streams. Components get a plain Observable and don't know about the multiplex protocol.

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...