share vs shareReplay in RxJS: what is the difference
AdvancedAngular interview questionBy UIRound, updated 3 December 2026
Short answer
Both operators multicast: many subscribers share one subscription to the source instead of each running it again. share() passes on only the values emitted after you subscribe, and by default disconnects from the source when the last subscriber leaves. shareReplay(n) also replays the last n values to late subscribers, and by default keeps its source subscription alive even when nobody is listening. Replay is the difference; refCount is the trap.
The problem both solve
Most observables are cold: each subscription runs the source again. In Angular that means two requests for one call.
const user$ = this.http.get<User>("/api/me");
user$.subscribe(renderHeader); // request 1
user$.subscribe(renderMenu); // request 2The same happens in a template that uses user$ | async twice. Multicasting puts a Subject between the source and the subscribers, so the source runs once and every subscriber receives the same values.
share(): one subscription, no memory
const ticks$ = interval(1000).pipe(
tap((n) => console.log("work", n)),
share(),
);The first subscriber connects to the source. Later subscribers join the same subscription but only see values emitted after they join. When the subscriber count drops to zero, share() unsubscribes from the source, and the next subscriber starts it fresh.
By default share() also resets when the source errors or completes, so a subscriber that arrives after an HTTP call has completed triggers a new request. That makes share() a poor cache. It is good for live streams that many parts of the page watch at once: a WebSocket feed, a fromEvent stream, a timer.
shareReplay(): one subscription plus a buffer
const config$ = this.http.get<Config>("/api/config").pipe(
shareReplay(1),
);shareReplay multicasts through a ReplaySubject, so a late subscriber immediately receives the last n values. For a single HTTP call, shareReplay(1) turns the observable into a cache: the first subscriber triggers the request, everyone after gets the stored response. The docs say a source that completed successfully stays cached forever, while one that errored can be retried by the next subscriber.
Always pass a buffer size. With no arguments, the buffer size is Infinity, so every value the source has ever emitted is kept and replayed.
Side by side
share() |
shareReplay(n) |
|
|---|---|---|
| Late subscriber gets old values | No | Yes, the last n |
| Subject used inside | Subject |
ReplaySubject(n) |
| Disconnects when subscribers reach 0 | Yes, by default | No, unless refCount: true |
| After the source completes | Resets, next subscriber resubscribes | Stays cached forever |
| After the source errors | Resets | Resets, so it can be retried |
| Good for | Live streams watched by many | Caching a result, late subscribers |
In RxJS 7, shareReplay is built on share. Its source code is share({ connector: () => new ReplaySubject(bufferSize, windowTime, scheduler), resetOnError: true, resetOnComplete: false, resetOnRefCountZero: refCount }). So you can read every difference in the table straight off that config.
The refCount trap
shareReplay defaults to refCount: false. The docs explain that this keeps the inner ReplaySubject subscribed to the source even when every subscriber has gone, and "potentially run for ever". For an HTTP call that completes, that does not matter. For an endless source it is a leak:
// Keeps polling after the component is destroyed
const prices$ = timer(0, 5000).pipe(
switchMap(() => this.http.get<Price[]>("/api/prices")),
shareReplay(1),
);
// Stops when the last subscriber unsubscribes
const prices$ = timer(0, 5000).pipe(
switchMap(() => this.http.get<Price[]>("/api/prices")),
shareReplay({ bufferSize: 1, refCount: true }),
);With refCount: true, the source is unsubscribed when the count reaches zero, and the next subscriber gets a new ReplaySubject and a fresh subscription. Use the object form whenever the source does not complete on its own.
You can implement the replay buffer and reference counting yourself in Implement RxJS BehaviorSubject, ReplaySubject, AsyncSubject and shareReplay with refCount, after building a plain multicasting Subject. The subjects themselves are compared in Subject vs BehaviorSubject vs ReplaySubject vs AsyncSubject.
Tuning share() instead
share() takes a config object, so you can get behaviours in between. A delayed reset keeps the connection alive briefly, which avoids a resubscribe when one component unmounts and another mounts right after:
const feed$ = webSocket<Message>(url).pipe(
share({ resetOnRefCountZero: () => timer(1000) }),
);Each reset* option takes true, false or a function returning an observable that decides when to reset.
Common follow-up questions
shareReplay or BehaviorSubject?
shareReplay(1) caches the result of a source you do not control, such as a request. A BehaviorSubject holds state that your own code changes with next(). Both give a late subscriber the latest value, but only the BehaviorSubject needs a starting value and lets you set new ones.
Why does a late subscriber get nothing with share()?
Because share() has no buffer. Values emitted before it subscribed are gone. If the source has completed, share() resets and the late subscriber starts the source again.
Does shareReplay leak memory?
Only with an endless source and refCount: false, or with no buffer size on a source that emits a lot. shareReplay({ bufferSize: 1, refCount: true }) covers both.
How do I refresh a shareReplay cache?
Build the cached observable again, or put a trigger in front of it: refresh$.pipe(startWith(null), switchMap(() => http.get(url)), shareReplay(1)). Each refresh$ emission fetches again and replaces the replayed value.
What happened to publish and refCount?
RxJS 7 deprecated multicast, publish, publishReplay, refCount and ConnectableObservable, and plans to remove them in RxJS 8. Use share with a config, or connectable for the rare case where you call connect() by hand.
Mistakes to avoid
Using
share()as a cache; it resets after the source completesUsing
shareReplay()with no buffer size and keeping every value foreverLeaving
refCountatfalsefor polling, WebSocket or timer sourcesPutting
shareReplayinside a method that builds a new observable on every call, so nothing is ever sharedPlacing
shareReplaybefore operators that each subscriber should run separately, or after ones that should run once; its position in the pipe decides what is shared
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Implement RxJS
BehaviorSubject,ReplaySubject,AsyncSubjectandshareReplaywithrefCountMedium45 min - Implement an
Observablewith operators and teardownHard50 min - Build an Observable Subject that multicasts to many subscribersMedium45 min
- Build Angular pure and impure pipes and an
AsyncPipethat switches sources and ignores late valuesMedium35 min - Implement Observable
from,intervalandfromEventwith teardownMedium40 min