Skip to the page

RxJS · core

Observables, cold and hot, subjects and shareReplay

An Observable is lazy and cold: each subscriber starts its own work. Subjects multicast. shareReplay shares one subscription and replays the last value.

The notes

What you must know

  • Promise: one value, eager, cannot be cancelled, always async. Observable: zero to many values over time, lazy, cancelled by unsubscribing.
  • HttpClient Observables are cold: each subscribe sends a request. Two async pipes on the same Observable send two requests.
  • Fixes: one subscription (@if (profile$ | async; as profile)), toSignal(...), or httpResource.
  • Subject: multicast, no current value. Late subscribers miss earlier values.
  • BehaviorSubject: needs an initial value, keeps the latest one and gives it to every new subscriber. getValue() reads it.
  • ReplaySubject(n, windowTime) replays the last n values. With no limit it keeps everything: a memory risk.
  • shareReplay(1) uses one subscription to the source and replays the last value to new subscribers.
  • With refCount: false (the default for the number form) it stays subscribed with no subscribers. Fine for a completing HTTP call, a leak for endless sources such as interval or a WebSocket.

The red pen

Common traps: mistake → fix

  • Mistake: An Observable runs when it is created

    Fix: nothing happens until you subscribe.

  • Mistake: shareReplay is always safe for caching

    Fix: with endless sources it can leak.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the difference between an Observable and a Promise?
  2. Why does my page send two requests?
  3. When do you use BehaviorSubject instead of Subject?
  4. What is the danger of shareReplay?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview