BACK
Use casesSSE wrapper — a custom Observable with teardown
Use cases · 49

SSE wrapper — a custom Observable with teardown

Pattern

EventSource (Server-Sent Events), an SDK with a callback API, legacy libraries — these aren't Observables. To use them in an RxJS pipeline, wrap them with new Observable(observer => {...}) and explicit teardown.

The problem it solves

Wrap it "from the outside" — add a listener in ngOnInit, remove it in ngOnDestroy — and it's easy to forget one of the steps. Especially when the code moves between components. The open connection keeps living after you leave the page.

Operators and why they matter

  • new Observable(observer => {...}) — the constructor. Inside, open the resource (EventSource, listener) and call observer.next(...) on events.
  • The return from the constructor is the teardown function. It's called on unsubscribe. Here we close the resource.
  • observer.next / observer.error / observer.complete — the standard methods for emitting.

Gotchas

  • Forget to return teardown and the connection stays open after unsubscribe. A leak.
  • Don't call observer.next after unsubscribe. Clear timers in teardown.
  • SSE/WebSocket aren't HTTP one-shots. shareReplay and refCount need careful setup so you don't hold the connection open forever.

What you get

Any callback API gets an RxJS lifecycle and is released correctly through unsubscribe.

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