Full answer
share() turns a cold source into one that is shared by all current subscribers. Internally it creates a Subject (the connector), subscribes to the source when the first subscriber arrives, and forwards values to every subscriber. The configuration object controls what happens afterwards:
connector: () => new Subject()(default): the subject that multicasts. Use() => new ReplaySubject(1)to replay the latest value to late subscribers.resetOnError: true(default): when the source errors, the next subscriber starts a new subscription. Setfalseto keep the failed state, or pass a function that returns an observable for a delayed reset.resetOnComplete: true(default): when the source completes, a later subscriber starts again. Setfalseto keep the completed state (late subscribers see only completion, or the replayed values if you use a ReplaySubject).resetOnRefCountZero: true(default): when the last subscriber unsubscribes, the source is unsubscribed and the state is reset. Setfalseto keep the source running with no listeners, or pass a function, for example() => timer(5000), to keep it alive for a grace period, which avoids restarting during quick navigations.
shareReplay({ bufferSize, refCount }) is a shortcut: share({ connector: () => new ReplaySubject(bufferSize), resetOnError: true, resetOnComplete: false, resetOnRefCountZero: refCount }). So shareReplay(1) keeps the source subscribed after the last subscriber leaves, and keeps the last value after completion, which is what you want for an HTTP result cache.
Choosing:
- Shared live stream (WebSocket, polling):
share(), perhaps withresetOnRefCountZero: () => timer(3000)so a quick route change does not reconnect. - Cached HTTP result for the session:
shareReplay(1)(source completes, so no leak). - Page-level replay without leaks:
shareReplay({ bufferSize: 1, refCount: true }).
Remember: sharing hides retries. Put retry before share so all subscribers benefit from one retry loop, and decide where errors should surface.
import { Observable, ReplaySubject, share, timer } from 'rxjs';
function source(name: string, log: string[]): Observable<number> {
return new Observable<number>((subscriber) => {
log.push(`${name}: subscribed`);
subscriber.next(1);
return () => log.push(`${name}: torn down`);
});
}
const log: string[] = [];
const plain$ = source('plain share', log).pipe(share());
const replayed$ = source('replay share', log).pipe(share({ connector: () => new ReplaySubject(1), resetOnRefCountZero: false }));
const grace$ = source('grace share', log).pipe(share({ resetOnRefCountZero: () => timer(30) }));
const a = plain$.subscribe();
a.unsubscribe();
plain$.subscribe().unsubscribe(); // source subscribed twice: it reset
const b = replayed$.subscribe();
b.unsubscribe();
replayed$.subscribe().unsubscribe(); // same source subscription is kept
const c = grace$.subscribe();
c.unsubscribe();
grace$.subscribe().unsubscribe(); // within 30 ms: the source is reused
setTimeout(() => {
console.log(log.join('\n'));
process.exit(0);
}, 80);RxJS 7.8. The script was run in Node 24 twice with identical output. It counts subscriptions to the source for three configurations.
Key points
- `share` multicasts through a Subject and resets on error, complete and zero subscribers by default.
- `connector` with a `ReplaySubject` replays values. `resetOnRefCountZero` can be a delay function.
- `shareReplay` is `share` with a ReplaySubject, `resetOnComplete: false` and a `refCount` setting.
- Put `retry` before `share`.
Common mistakes
- Assuming `share` replays the latest value to late subscribers.
- Using `shareReplay(1)` on an endless source and leaking it.
- Putting `retry` after `share`, so each subscriber retries separately.
Follow-ups
- How would you keep a WebSocket open for 5 seconds after the last subscriber leaves?
- What happens to a late subscriber after the source completes in each setting?
- Why is HTTP a safe case for `shareReplay(1)`?
Tips
- Write the `shareReplay` equivalent as `share` options. It proves understanding.
- Mention the grace period option.
- State where `retry` goes.
Evaluation rubric
- Explains each share option correctly.
- Relates shareReplay to share.
- Chooses configuration for real cases.