The RxJS shareReplay Operator Explained With Examples
Learn how RxJS shareReplay shares one subscription and replays recent values to late subscribers, and why refCount decides whether it leaks.

A cold observable does its work once per subscriber. Subscribe three times to an HTTP request and the server gets three requests. shareReplay turns that around: it subscribes to the source once, shares that single subscription between everyone, and remembers the last values so that a subscriber arriving later still gets something. It is the usual way to cache the result of an expensive observable in a service. It also has a famous trap, a subscription that never closes, which RxJS 7 fixed with an explicit refCount option. This post explains shareReplay with printed output, shows the effect on the number of source subscriptions, covers the buffer size, the leak and the fix, and lists the cases where it is the wrong tool.
The problem it solves
import { defer, of } from "rxjs";
let requests = 0;
const user$ = defer(() => {
requests += 1;
console.log(`request ${requests}`);
return of({ name: "Ada" });
});
user$.subscribe((u) => console.log("A", u.name));
user$.subscribe((u) => console.log("B", u.name));request 1
A Ada
request 2
B AdaTwo subscribers, two requests. When several components of an app read the same value, that is wasteful and can show inconsistent data.
The fix
import { defer, of } from "rxjs";
import { shareReplay } from "rxjs/operators";
let requests = 0;
const user$ = defer(() => {
requests += 1;
console.log(`request ${requests}`);
return of({ name: "Ada" });
}).pipe(shareReplay(1));
user$.subscribe((u) => console.log("A", u.name));
user$.subscribe((u) => console.log("B", u.name));request 1
A Ada
B AdaOne request. The second subscriber received the replayed value without triggering new work. shareReplay(1) multicasts through an internal ReplaySubject with a buffer of one value.
Late subscribers
Replay is what separates it from a plain share. A subscriber that arrives after the value was emitted still gets it.
import { Subject } from "rxjs";
import { shareReplay } from "rxjs/operators";
const source$ = new Subject();
const shared$ = source$.pipe(shareReplay(2));
shared$.subscribe((v) => console.log("early", v));
source$.next(1);
source$.next(2);
source$.next(3);
shared$.subscribe((v) => console.log("late", v));early 1
early 2
early 3
late 2
late 3The buffer size of 2 kept the last two values. The late subscriber got both immediately, then would receive any later values live. shareReplay(1) is the typical choice for "current state", since a newcomer needs only the latest.
The leak, and refCount
By default, shareReplay(1) keeps the source subscription alive even after every subscriber leaves, which is refCount: false. RxJS 7 added the option to change that. For a source that never completes, such as an interval, that means the work runs forever.
import { interval } from "rxjs";
import { shareReplay, take, tap } from "rxjs/operators";
const ticks$ = interval(20).pipe(
tap((n) => console.log("source tick", n)),
shareReplay(1)
);
const sub = ticks$.pipe(take(2)).subscribe((n) => console.log("got", n));source tick 0
got 0
source tick 1
got 1
source tick 2
source tick 3
source tick 4The subscriber took two values and left, and the source kept ticking. The output continues indefinitely, because the shared subscription stayed open. With refCount: true, the source is unsubscribed when the last subscriber leaves.
import { interval } from "rxjs";
import { shareReplay, take, tap } from "rxjs/operators";
const ticks$ = interval(20).pipe(
tap((n) => console.log("source tick", n)),
shareReplay({ bufferSize: 1, refCount: true })
);
ticks$.pipe(take(2)).subscribe((n) => console.log("got", n));source tick 0
got 0
source tick 1
got 1Now it stops. The cost is that after everyone has left, a new subscriber restarts the source from scratch, instead of getting a cached value. That is the trade: refCount: true frees resources, refCount: false keeps the cache.
Which setting to use
| Source | Setting | Why |
|---|---|---|
| One-shot HTTP request that completes | shareReplay(1) | the source completes, so nothing leaks, and the value stays cached |
| Endless stream (interval, websocket, store) | shareReplay({ bufferSize: 1, refCount: true }) | lets the source stop when nobody listens |
| Result that must be refreshed on demand | not shareReplay | the cache never expires |
A completed source is safe with the simple form. After completion, shareReplay replays the buffered values and the completion to new subscribers without resubscribing to the source.
Errors are not cached
If the source errors, shareReplay forwards the error and, in RxJS 7, resets, so the next subscriber triggers a fresh attempt.
import { defer, of, throwError } from "rxjs";
import { shareReplay } from "rxjs/operators";
let calls = 0;
const flaky$ = defer(() => {
calls += 1;
return calls === 1 ? throwError(() => new Error("first failed")) : of("ok");
}).pipe(shareReplay(1));
flaky$.subscribe({ error: (e) => console.log("A:", e.message) });
flaky$.subscribe({ next: (v) => console.log("B:", v) });A: first failed
B: okThat is usually what you want for requests: a failure should not be remembered forever. Pair it with retry if the failure should be retried inside the shared stream.
A service example
import { defer, of } from "rxjs";
import { delay, shareReplay, tap } from "rxjs/operators";
class ConfigService {
config$ = defer(() => {
console.log("loading config");
return of({ theme: "dark" }).pipe(delay(10));
}).pipe(shareReplay(1));
}
const service = new ConfigService();
service.config$.subscribe((c) => console.log("header", c.theme));
service.config$.subscribe((c) => console.log("sidebar", c.theme));
setTimeout(
() => service.config$.subscribe((c) => console.log("footer", c.theme)),
50
);loading config
header dark
sidebar dark
footer darkThe footer subscribed after the load finished and got the cached value with no second load. This is the pattern behind most "load once, read many" services.
shareReplay versus share
share() multicasts without a buffer: a late subscriber sees only values emitted after it subscribed. Since RxJS 7, share accepts reset options and can replay through connector: () => new ReplaySubject(1), and shareReplay is a preconfigured form of it.
Common mistakes
**Using shareReplay(1) on an endless stream without refCount.** The source runs forever. Set refCount: true.
Expecting the cache to refresh. The buffer holds the first result until the stream completes or resets. Use a refresh trigger and switchMap if data can go stale.
Placing it before operators that should be shared. Operators after shareReplay run per subscriber. Put it after the expensive work, at the end of the shared chain.
Caching a mutable object. Every subscriber gets the same reference. Mutate it and everyone sees the change.
Creating a new shared observable on each call. A method that returns source$.pipe(shareReplay(1)) creates a fresh cache per call. Store the shared observable in a property.
Memory and the buffer
A replayed value is a reference held for as long as the shared stream lives. If the value is a large response, such as a list of ten thousand records, it stays in memory while any subscriber or the cache itself is alive, and with refCount: false that can be as long as the application. For data that should not be pinned, either use refCount: true so that the buffer is dropped when nobody listens, or hold the cache in a structure with its own eviction policy and expose it through a function that returns an observable.
The buffer size also matters. shareReplay(1) stores one value. A larger number stores that many past emissions, replayed in order to every new subscriber, which is rarely what a state stream wants and can lead to a burst of stale values when a component subscribes late. Use a size greater than one only for event history that a newcomer legitimately needs to see.
Invalidating a cached result
Because shareReplay never expires, caching with it needs an explicit way to refresh. A common design keeps a refresh$ subject, and builds the shared stream as refresh$.pipe(startWith(undefined), switchMap(() => request()), shareReplay(1)). Emitting on refresh$ runs the request again, and every subscriber receives the new value through the same shared stream. This gives you the benefits of a single request and a single cached value, with an obvious place to expire it after a save or on a timer.
When a store or query library is better
Hand-rolled caches grow requirements: stale-while-revalidate, request deduplication across keys, retries and garbage collection. If you find yourself adding those to a shareReplay chain, a query library built for the purpose will handle them with fewer bugs, and the observable can wrap its output.
A checklist for caching with it
Before you add shareReplay to a service, check four things. The source completes or you have set refCount. The cached value is small enough to hold for the life of the application, or you are happy for it to be dropped. The value does not go stale in a way the user will notice, or there is a refresh path. And the shared observable is stored once, in a property or a constant, so that every consumer shares the same instance and not a fresh copy.


