| | |

RxJS 10 ๐ŸŸฃ Hot vs. Cold & Multicasting โ€” Sharing stream execution cleanly with share, shareReplay, and connectable

โฑ๏ธ Estimated read: 26 min | |

Every observable in RxJS is either cold or hot, and the distinction is about where the producer lives. A cold observable creates its producer when it is subscribed: http.get('/api/user') issues the request at subscribe time, of(1, 2, 3) materialises the values at subscribe time, interval(1000) starts its timer at subscribe time. Two subscriptions mean two requests, two arrays, two timers. A hot observable relies on a producer that exists independently: a Subject, a WebSocketSubject, a fromEvent stream over a DOM element that fires whether or not anyone is listening.

That split has a direct consequence for any component that needs the same data twice. Two widgets that both need the current user both subscribe to http.get('/api/user') and both make the request. Two directives that both listen for a resize both add a listener and both run their handler when the resize fires. The observable’s producer is not shared by default, and the fix is an operator that turns one cold source into one hot subscription โ€” a multicast.

The three operators in this chapter are the modern multicast tools, and they differ only in what happens to the source subscription and to the values. share() subscribes on the first subscriber and unsubscribes on the last, with no cache. shareReplay() adds a buffer so a late subscriber receives the most recent value immediately. connectable() gives you explicit control over when the source is subscribed and when it is torn down. Everything else is a config flag on one of those three.

This chapter starts with why the cold/hot distinction is not academic โ€” it is the source of duplicate requests, duplicate listeners, and out-of-sync UI โ€” then walks each operator with its exact subscription lifecycle, then assembles a service where all three appear on the sides of the code where they belong.

Key point: a multicast operator does not change the values; it changes who runs the producer. share() runs it once and drops it on the last unsubscribe. shareReplay() runs it once, caches the buffer, and keeps the cache across subscribers. connectable() runs it when you say so and stops when you say so. Pick by which lifecycle you need, not by which one sounds like “share”.


Why multicasting exists

The duplicate-request problem. The most visible bug in every RxJS codebase is the same fetch fired twice because two components subscribed to the same cold observable. The browser tab shows two calls in the network tab, the backend receives two requests, and nothing in the code looks wrong because the observable is constructed once and subscribed twice. share() collapses those two subscriptions into one upstream subscription; the second subscriber joins the first rather than starting its own.

The duplicate-listener problem. fromEvent(window, 'resize') is different from http.get. The DOM event source is inherently hot โ€” the browser emits resize regardless of subscribers โ€” but every RxJS subscription registers a fresh listener. Ten directives with ten subscriptions means ten listeners and ten handler invocations per resize. share() reduces them to one listener, and the ten directives all receive the same event through the one subscription. The producer is shared even though the events were already there.

The out-of-sync problem. Two independent subscriptions to interval(1000) start their own timers, and the two timers drift apart. Two subscribers to a cold concat stream see the same values but on independent schedules. Sharing the subscription makes both subscribers hear the exact same emission at the exact same time, which is what a header, a footer, and a sidebar all rendering “the current second” actually need.

The cache-once problem. A navigation menu that refetches the user’s profile every time the menu is opened is slow and wasteful. The profile has not changed. shareReplay({ bufferSize: 1, refCount: true }) makes the first fetch run once and caches the result, so subsequent subscriptions receive the cached value without issuing a new request. This is not a general-purpose cache โ€” there is no TTL and no invalidation โ€” but it covers the common case of a screen that remounts faster than the data changes.

The lifecycle-ownership problem. Some sources must be subscribed and unsubscribed on a schedule that does not match any single consumer. A WebSocket that should be open whenever any component needs it, but also must close on logout โ€” that lifecycle belongs to the service, not to a component. connectable() gives the service a .connect() method and a subscription handle. The service decides when the source runs; components subscribe and unsubscribe freely without triggering connect/disconnect.

The refCount-gotcha problem. The default share() unsubscribes the source when the last subscriber drops and subscribes again on the next one. For an HTTP call that completed, that means the next subscriber re-fires the request. For a socket, it means a reconnection. The behaviour is correct for a source that should not run when nobody is listening, and wrong for a source that should be cached after it completed. The three operators are largely about choosing which of those two behaviours you get.


a. Cold and hot โ€” the two execution models

A cold observable has a producer that is created by each subscription. The values only exist while someone is subscribed, and each subscriber has its own emission timeline. A hot observable has a producer that exists independently; the observable is a view onto it, and every subscriber receives values from the same timeline.

import { of, interval } from 'rxjs';

// Cold: nothing happens at definition time
const cold$ = of(1, 2, 3);

cold$.subscribe((v) => console.log('A:', v));  // A: 1, A: 2, A: 3
cold$.subscribe((v) => console.log('B:', v));  // B: 1, B: 2, B: 3
// Two independent executions of the "materialise 1, 2, 3" logic

// Cold interval: each subscriber has its own timer
const tick$ = interval(1000);

tick$.subscribe((n) => console.log('A:', n));  // A: 0 at t=1000
setTimeout(() => {
  tick$.subscribe((n) => console.log('B:', n)); // B: 0 at t=1500
}, 500);                                       // A and B drift apart

The interval case shows the drift explicitly. Subscriber A’s first 0 arrives at t=1000 ms; subscriber B’s first 0 arrives at t=1500 ms, half a second later, because B’s timer started later. Two independent executions, two timelines.

A hot observable is the opposite. Subject is the canonical example โ€” you call .next, every current subscriber receives it, and there is exactly one producer.

import { Subject, fromEvent } from 'rxjs';

// Hot: values exist independent of subscription
const hot$ = new Subject<number>();

hot$.subscribe((v) => console.log('A:', v));
hot$.subscribe((v) => console.log('B:', v));

hot$.next(1);           // A: 1, B: 1 (one push, two deliveries)
hot$.next(2);           // A: 2, B: 2

// fromEvent is hot in the source sense: the browser emits
// regardless of RxJS subscribers, but each RxJS subscription
// registers its own DOM listener
const resize$ = fromEvent(window, 'resize');
resize$.subscribe(handler1);   // adds listener 1
resize$.subscribe(handler2);   // adds listener 2
// One resize event fires once per listener = twice

fromEvent is worth pinning down because it looks hot and behaves cold. The events are hot โ€” the browser produces them whether or not anyone listens. But each RxJS subscription adds its own DOM listener, so handler1 and handler2 above run separately. The share() operator removes that per-subscription work, leaving one listener and a single multicasted stream.

The distinction compresses to one question: does subscribing create a producer, or attach to an existing one? http.get, of, interval, timer, range, defer, from all create on subscribe. Subject, BehaviorSubject, ReplaySubject, AsyncSubject, fromEvent, WebSocketSubject, from over an iterator after the first pull, and anything already piped through share() are already hot.


b. share() โ€” multicast with automatic refCount

share() makes one cold source look hot. The first subscriber attaches and triggers the source subscription. Every subsequent subscriber attaches to the same source subscription and does not start the work again. When the last subscriber detaches, the source is unsubscribed. share() is exactly the composition of publish() plus refCount() from older RxJS, in a single operator.

import { interval } from 'rxjs';
import { share, take } from 'rxjs/operators';

const tick$ = interval(1000).pipe(
  take(3),
  // One underlying interval, multiple subscribers
  share()
);

tick$.subscribe((n) => console.log('A:', n));   // A: 0 at t=1000
setTimeout(() => {
  tick$.subscribe((n) => console.log('B:', n)); // B: 1 at t=2000 (not 0)
}, 1500);

// Output:
//   A: 0  (at t=1000)
//   B: 1  (at t=2000, B joined mid-stream and missed A: 0)
//   A: 1  (at t=2000)
//   A: 2  (at t=3000)
//   B: 2  (at t=3000)
//   complete for both

The output shows the contract precisely. A and B share one interval. When B joins at t=1500, it does not receive the 0 that already fired โ€” a plain Subject has no memory, and share() uses a plain Subject as its connector. B receives 1 and 2 alongside A and completes when A completes. Two subscribers, one producer.

The refCount behaviour is the important part. When the count drops to zero, share() unsubscribes the source. When a new subscriber arrives later, share() re-subscribes to the source โ€” starting a fresh execution, not resuming the old one. For an HTTP call this means a second subscriber after all the first subscribers left causes a second request.

import { timer } from 'rxjs';
import { share, map } from 'rxjs/operators';

const fetch$ = timer(500).pipe(
  map(() => ({ user: 'Alice' })),
  // Multicasted, but NOT cached: every "batch" refetches
  share()
);

// First batch: 1 request
const sub1 = fetch$.subscribe((u) => console.log('A:', u));
const sub2 = fetch$.subscribe((u) => console.log('B:', u));

// Both leave; refCount hits 0; source unsubscribed
setTimeout(() => {
  sub1.unsubscribe();
  sub2.unsubscribe();
}, 1000);

// Second batch: NEW request
setTimeout(() => {
  fetch$.subscribe((u) => console.log('C:', u));   // runs the timer again
}, 2000);

The output is two separate requests. Subscribers A and B share the first one; subscriber C gets a fresh one because the refCount went to zero and the source was re-executed. This is correct for a source that should only run when someone is listening and wrong for a source whose result should be cached.

share() also takes a config object, covered in section e:

import { share, ReplaySubject } from 'rxjs';

const cached$ = source$.pipe(
  share({
    connector: () => new ReplaySubject(1),   // cache the last value
    resetOnError: true,
    resetOnComplete: false,
    resetOnRefCountZero: false               // keep the source alive
  })
);

c. shareReplay() โ€” multicast with a retained buffer

shareReplay() is share() with a ReplaySubject as its connector. A late subscriber receives the buffered values synchronously on subscribe, then all subsequent emissions. The two parameters that matter are bufferSize and refCount.

import { interval } from 'rxjs';
import { shareReplay, take } from 'rxjs/operators';

const tick$ = interval(1000).pipe(
  take(4),
  // Buffer the last value; unsubscribe the source when the last
  // subscriber leaves, but keep the buffered value
  shareReplay({ bufferSize: 1, refCount: true })
);

tick$.subscribe((n) => console.log('A:', n));    // A: 0 at t=1000
setTimeout(() => {
  tick$.subscribe((n) => console.log('B:', n));  // B: 1 immediately (cached)
}, 2500);

Subscriber B joins at t=2500. The most recent emission was 1 at t=2000, which is in the buffer. B receives 1 synchronously on subscribe, then 2 and 3 alongside A, then complete. No second timer, no second interval, no missed values after the cached one.

The refCount flag decides when the source is torn down.

// refCount: true โ€” source unsubscribed when the last subscriber leaves;
// buffer retained; a new subscriber triggers a re-subscription to
// the source (if not completed) and receives the buffer first
shareReplay({ bufferSize: 1, refCount: true })

// refCount: false โ€” source subscribed on first subscriber and NEVER
// unsubscribed; buffer retained forever; the connector lives forever
// with the operator's containing subscription
shareReplay({ bufferSize: 1, refCount: false })

refCount: false is the leak. On a long-lived stream โ€” a WebSocket, an interval, an event source that never completes โ€” the source subscription outlives every subscriber and is never torn down. The buffer grows if bufferSize is unbounded, or holds one value forever if it is 1. On component unmount there is no unsubscription, and the resource stays open until the process ends.

// LEAK: refCount false; the source and buffer never release
const socket$ = webSocket('wss://api.example.com').pipe(
  shareReplay({ bufferSize: 1, refCount: false })
);
// Every navigation that subscribes issues no new socket, but the one
// socket that was opened stays open for the lifetime of the app

// CONTROLLED: refCount true; the socket closes when the last consumer leaves
const socket$ = webSocket('wss://api.example.com').pipe(
  shareReplay({ bufferSize: 1, refCount: true })
);

refCount: true has its own version-sensitive edge case. In some RxJS 7.x releases, when the source had completed and refCount dropped to zero, the buffer was reset, and a subsequent subscriber triggered a re-subscription to a completed source that emitted nothing. The pattern is stable in current releases, but for HTTP-style caching the recommendation has shifted toward an explicit share({ connector: () => new ReplaySubject(1), resetOnRefCountZero: false }). Both forms are valid; the explicit one gives precise control.

The refCount: true case is what most HTTP caching wants:

import { of } from 'rxjs';
import { delay, shareReplay, switchMap } from 'rxjs/operators';

// Cache an HTTP response for the lifetime of the service
const profile$ = userId$.pipe(
  switchMap((id) => http.get<User>(`/api/users/${id}`)),
  shareReplay({ bufferSize: 1, refCount: true })
);

profile$.subscribe(renderHeader);     // 1 request
profile$.subscribe(renderSidebar);    // uses same request
// All leave; refCount hits 0; buffer retained
// Later subscriber: gets cache, no new HTTP call

The window of caching is the buffer’s lifetime. With refCount: true, that is forever once the source completes โ€” every future subscriber receives the cached response until the observable is recreated or the buffer is reset. That is exactly what a page-scoped service wants.


d. connectable() โ€” explicit connect control

connectable(source, config?) returns a ConnectableObservable<T> that does not subscribe to the source until .connect() is called. Subscribers attach to the underlying subject freely; the source subscription starts only on connect(), and .disconnect() (or the returned subscription’s unsubscribe) tears it down.

import { interval, connectable, Subject } from 'rxjs';
import { take } from 'rxjs/operators';

const source$ = interval(1000).pipe(take(5));

const connectable$ = connectable(source$, {
  connector: () => new Subject<number>(),
  resetOnDisconnect: false
});

// Subscribers arrive; the source is NOT running yet
const subA = connectable$.subscribe((n) => console.log('A:', n));
const subB = connectable$.subscribe((n) => console.log('B:', n));

// Now the source starts: one subscription to interval, delivered to both
const connection = connectable$.connect();

// Later, tear down the source subscription
setTimeout(() => connection.unsubscribe(), 3500);

The connect() call starts the underlying interval. The two subscribers receive every emission from the single subscription. connection.unsubscribe() tears down the source; the two subscribers receive complete (because the source was taken to 5 and completed, or because the disconnect fired).

The interesting case is a WebSocket that must be open when the user is logged in regardless of which component is mounted. share() would open the socket on the first subscriber and close it on the last โ€” which means a brief gap when navigating between two components that both want the socket. connectable() keeps the socket open across that gap.

import { webSocket, connectable, Subject, filter, map } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

class SessionService {
  private socket$ = connectable(webSocket('wss://api.example.com'), {
    connector: () => new Subject<Message>(),
    resetOnDisconnect: false
  });

  private connection: Subscription | null = null;

  login(token: string): void {
    // Open the socket at login: one connection for the session
    this.connection = this.socket$.connect();
  }

  logout(): void {
    // Close the socket at logout: the source stops
    this.connection?.unsubscribe();
    this.connection = null;
  }

  messages$ = this.socket$.asObservable();
}

The connectable source is subscribed once, at login, and torn down once, at logout. Any number of components can subscribe to messages$ in between; none of them trigger a connect or a disconnect. That is the lifecycle pattern for sources that belong to the application session rather than to any component’s lifetime.

resetOnDisconnect: true (which is the default if connectable is called without options and a fresh source is required) means the source is re-subscribed on the next connect() call. resetOnDisconnect: false means the connector and the internal state are reset when .connect() was never called after a disconnect. Do not over-model that; the .unsubscribe() pattern in the example is the version you want for sockets.


e. The ShareConfig reference

share() accepts a ShareConfig<T> object that duplicates the flexibility of the older publish() and multicast() operators. Five fields, each with a sensible default.

import { share, Subject, ReplaySubject } from 'rxjs';

const shared$ = source$.pipe(
  share({
    // Which Subject type to use as the connector. Default Subject.
    connector: () => new ReplaySubject(1),
    // Reset the connector on an error; new subscriber starts clean.
    resetOnError: true,
    // Reset the connector on completion; a new subscriber restarts.
    resetOnComplete: false,
    // Reset the connector when refCount hits zero; source unsubscribes.
    resetOnRefCountZero: true
  })
);

The four flags interact in specific ways, and knowing them means share() covers every case shareReplay covers.

resetOnError: true (default) means an error propagates to every current subscriber and resets the pipeline. The next subscriber gets a fresh source. resetOnError: false errors the source once and the error is retained for all future subscribers โ€” useful for a fatal initialisation failure where retrying is not meaningful.

resetOnComplete: false (default) means the source is not re-subscribed after it completes. This is what makes share() cache a completed HTTP call: after the first completion, all future subscribers receive complete immediately from the same subject. Hmm โ€” but the subject has no buffer, so they receive only complete and no values. Set resetOnComplete: true if new subscribers should trigger a fresh request.

resetOnRefCountZero: true (default) means the source is unsubscribed when the last subscriber leaves, and the connector is reset. The next subscriber starts fresh. Set resetOnRefCountZero: false to keep the source subscribed after refCount hits zero โ€” the exact behaviour of shareReplay({ refCount: false }).

For an HTTP cache that survives a completed request:

import { ReplaySubject, share } from 'rxjs';

const profile$ = http.get<User>('/api/profile').pipe(
  share({
    connector: () => new ReplaySubject(1),
    resetOnError: true,
    resetOnComplete: false,   // keep the buffer after the HTTP completes
    resetOnRefCountZero: false // keep the buffer after refCount hits zero
  })
);

Both resetOnComplete: false and resetOnRefCountZero: false are needed for the “cache forever once loaded” case. With resetOnComplete: true, the buffer would clear on the response’s completion. With resetOnRefCountZero: true, the buffer would clear when the last subscriber left. Setting both to false gives the behaviour of a well-behaved shareReplay without the refCount: true edge cases.

For the “cache until everyone leaves” case:

const profile$ = http.get<User>('/api/profile').pipe(
  share({
    connector: () => new ReplaySubject(1),
    resetOnRefCountZero: true      // clear the buffer on refCount 0
  })
);

The buffer clears when the last subscriber leaves. The next subscriber triggers a fresh HTTP call. That is shareReplay({ refCount: true }) expressed through share(), with the edge cases handled explicitly.


f. The deprecated operators and the migration

Before RxJS 7, the multicasting toolkit was a set of operators that combined a connectable observable with a refCount. publish(), publishReplay(), publishLast(), multicast(), and refCount() were all deprecated when share() and connectable() landed, and the migration path is mechanical.

// DEPRECATED: the RxJS 6 pattern
import { publish, refCount, publishReplay, multicast } from 'rxjs/operators';

source$.pipe(publish(), refCount());               // = share()
source$.pipe(publishReplay(1), refCount());        // = shareReplay({ bufferSize: 1, refCount: true })
source$.pipe(publishReplay(1));                    // = shareReplay({ bufferSize: 1, refCount: false })
source$.pipe(multicast(() => new Subject()));      // = connectable(source)

The first line is share() exactly. publish() returns a ConnectableObservable; refCount() converts it into an auto-connecting observable that subscribes on the first subscriber and unsubscribes on the last. That is the exact specification of share().

The second and third lines are shareReplay() with the two refCount values. publishReplay(1) + refCount() is the “cache with refcount” case; bare publishReplay(1) is the “cache forever, never unsubscribe” case. The couple of RxJS 6 codebases still in the wild are doing the second-to-last line in disguise.

The last line is connectable() with the Subject connector. The multicast() operator was the older form of connectable(), and its argument was a factory for the connector subject.

One further migration detail worth knowing: shareReplay(1) (the number form) is the legacy signature. It is deprecated in favour of shareReplay({ bufferSize: 1, refCount: false }). The number form had subtly different behaviour in old versions and is best avoided even in codebases where it still compiles.

The one operator that has no direct replacement is ReplaySubject used as a connector when the semantics of the connector are exotic. share({ connector: () => customSubject }) handles ordinary cases. A connector with custom logic can still be wrapped in a Subject and used directly, but the pattern is rare enough not to warrant one of the built-in operators.


Complete Example Session

// ============================================
// PART 1: IMPORTS AND SHARED VALUES
// ============================================
import {
  Subject, ReplaySubject, Observable,
  interval, timer, fromEvent, connectable
} from 'rxjs';
import {
  share, shareReplay, take, map, switchMap,
  filter, tap
} from 'rxjs/operators';

interface User { readonly id: number; readonly name: string; }

const userId$ = new Subject<number>();

// ============================================
// PART 2: COLD HTTP IS COLD โ€” ONE REQUEST PER SUBSCRIBER
// ============================================
const profile$ = userId$.pipe(
  switchMap((id) => http.get<User>(`/api/users/${id}`))
);

// Two subscribers, two requests:
profile$.subscribe((u) => console.log('A:', u.name));
profile$.subscribe((u) => console.log('B:', u.name));
// Network tab shows two GET /api/users/:id

// ============================================
// PART 3: share() โ€” MULTICAST, NO CACHE
// ============================================
const shared$ = userId$.pipe(
  switchMap((id) => http.get<User>(`/api/users/${id}`)),
  share()
);

shared$.subscribe((u) => console.log('A:', u.name));
shared$.subscribe((u) => console.log('B:', u.name));
// One request while both are subscribed; a new subscription after all
// have left triggers a fresh request

// ============================================
// PART 4: shareReplay({ REFCOUNT: TRUE }) โ€” CACHED, RELEASED ON ZERO
// ============================================
const cached$ = userId$.pipe(
  switchMap((id) => http.get<User>(`/api/users/${id}`)),
  shareReplay({ bufferSize: 1, refCount: true })
);

cached$.subscribe(renderHeader);       // 1 request
cached$.subscribe(renderSidebar);      // shares the same request
// Both leave; refCount 0; source unsubscribed (already complete); buffer kept
// Later subscriber receives cached user, no new request

// ============================================
// PART 5: shareReplay({ REFCOUNT: FALSE }) โ€” THE LEAK
// ============================================
// On a long-lived source, the source runs forever once subscribed
const socket$ = webSocket('wss://api.example.com').pipe(
  shareReplay({ bufferSize: 1, refCount: false })
);
// Safe only if the containing service is torn down with the app

// ============================================
// PART 6: connectable() โ€” MANUAL CONNECT AND DISCONNECT
// ============================================
const conn$ = connectable(
  webSocket('wss://api.example.com'),
  { connector: () => new Subject<Message>() }
);

const subA = conn$.subscribe((m) => handle(m));
const subB = conn$.subscribe((m) => log(m));

// Nothing happens until connect():
const connection = conn$.connect();

// Later, at logout:
// connection.unsubscribe();  the socket closes permanently

// ============================================
// PART 7: SHARE WITH EXPLICIT CONFIG โ€” CACHE FOREVER
// ============================================
const explicitCache$ = http.get<User>('/api/profile').pipe(
  share({
    connector: () => new ReplaySubject<User>(1),
    resetOnError: true,
    resetOnComplete: false,      // keep the buffer after HTTP completes
    resetOnRefCountZero: false   // keep the buffer after refCount zero
  })
);
// First subscription triggers the request; every later one is cached

// ============================================
// PART 8: fromEvent โ€” REMOVE DUPLICATE LISTENERS WITH share()
// ============================================
const resize$ = fromEvent(window, 'resize').pipe(
  share()
);
// Both directives share one DOM listener
resize$.subscribe(recalcHeader);
resize$.subscribe(recalcSidebar);
// Only ONE window.addEventListener('resize', ...) was called

// ============================================
// PART 9: THE GOTCHA โ€” share() RESETS ON COMPLETE
// ============================================
const fetcher$ = timer(500).pipe(
  map(() => ({ loaded: true })),
  share()
);
// First subscriber batches see one request; the source completes
fetcher$.subscribe((x) => console.log('A:', x));
// All leave; refCount 0

// LATER: no cache, so the source re-executes
fetcher$.subscribe((x) => console.log('B:', x));
// A second timer fires; not what a cache would do

// The fix, if a cache is wanted:
const fetcherCached$ = timer(500).pipe(
  map(() => ({ loaded: true })),
  shareReplay({ bufferSize: 1, refCount: true })
);

// ============================================
// PART 10: THE ASSEMBLED SERVICE
// ============================================
class ProfileService {
  // HTTP reads: cache once loaded, retain after refCount 0
  readonly user$ = this.userId$.pipe(
    switchMap((id) => http.get<User>(`/api/users/${id}`)),
    share({
      connector: () => new ReplaySubject<User>(1),
      resetOnComplete: false,
      resetOnRefCountZero: false
    })
  );

  // Socket writes: owned by the service lifetime
  private readonly socket$ = connectable(
    webSocket('wss://api.example.com'),
    { connector: () => new Subject<Message>() }
  );

  readonly messages$ = this.socket$.asObservable();

  private userId$ = new Subject<number>();
  private connection: Subscription | null = null;

  load(id: number): void { this.userId$.next(id); }

  connect(): void {
    this.connection = this.socket$.connect();
  }

  disconnect(): void {
    this.connection?.unsubscribe();
    this.connection = null;
  }
}

The ten parts showed the raw cold HTTP problem, the share() fix, the shareReplay cache with and without refCount, the connectable() manual lifecycle, the explicit share({ connector }) form, the fromEvent sharing case, the share() reset-on-complete gotcha, and finally a service that picks a different operator for reads versus sockets based on which lifecycle the code needs.


Quick Reference

The Three Operators

OperatorSource runsSource torn downLate subscriber
share()on first subscriberon last unsubscribereceives nothing
shareReplay({refCount: true})on first subscriberon last unsubscribereceives buffer
shareReplay({refCount: false})on first subscriberneverreceives buffer
connectable(source)on .connect()on .unsubscribe()receives nothing

ShareConfig Defaults

OptionDefaultEffect
connector() => new Subject()the subject used for multicasting
resetOnErrortrueerror terminates and resets the pipeline
resetOnCompletefalsecomplete leaves the subject complete
resetOnRefCountZerotruerefCount 0 unsubscribes the source

Common Patterns

PatternRecipe
Share one HTTP call across two widgetsshare()
Cache HTTP after load, retainshareReplay({ bufferSize: 1, refCount: true })
Cache forever, never releaseshare({ connector: () => new ReplaySubject(1), resetOnRefCountZero: false })
Cache and release on refCount 0share({ connector: () => new ReplaySubject(1), resetOnRefCountZero: true })
Session socket with explicit lifecycleconnectable(source).connect() at login
Share one DOM listener across directivesshare()
Share and no cache after completeshare()

Deprecated โ†’ Modern

DeprecatedModern
publish() + refCount()share()
publishReplay(1) + refCount()shareReplay({ bufferSize: 1, refCount: true })
publishReplay(1)shareReplay({ bufferSize: 1, refCount: false })
multicast(() => new Subject())connectable(source)
shareReplay(1) (number)shareReplay({ bufferSize: 1, refCount: true })

Best Practices

โœ… Do This:

// Share a single HTTP call across multiple subscribers
user$.pipe(share());                                                    // โœ…

// Cache the response once it loads
profile$.pipe(shareReplay({ bufferSize: 1, refCount: true }));          // โœ…

// Own a WebSocket's lifecycle explicitly
connectable(socket$).connect() at login; .unsubscribe() at logout      // โœ…

// Share a fromEvent stream so the DOM listener is registered once
resize$.pipe(share());                                                  // โœ…

// Use share({ connector }) when refCount semantics are subtle
share({ connector: () => new ReplaySubject(1), resetOnRefCountZero: false }); // โœ…

// Combine with takeUntil for component teardown after multicasting
shared$.pipe(takeUntil(destroy$)).subscribe(render);                    // โœ…

// Place share() after the source, before the consumers
source$.pipe(switchMap(...), share());                                  // โœ…

โŒ Don’t Do This:

// Expect share() to cache
fetcher$.pipe(share());        // re-fires after refCount 0        // โŒ

// shareReplay({ refCount: false }) on a long-lived source
socket$.pipe(shareReplay({ bufferSize: 1, refCount: false }));  // โŒ leak

// Multicast without unsubscribing on component teardown
shared$.subscribe(render);     // leaking the subscription        // โŒ

// share() before the side-effect operator inside a subscription
share().pipe(switchMap(...));   // the source starts on share      // โŒ

// Connect a connectable without tracking the returned subscription
connectable$.connect();         // no way to disconnect             // โŒ

// Use publish() + refCount() in new code
source$.pipe(publish(), refCount());                              // โŒ deprecated

Common Pitfalls

PitfallWhy It HappensFix
Duplicate HTTP requestsCold observable, two subscribersshare() or shareReplay()
Second subscriber curls anewshare() after source completed, refCount 0shareReplay({ bufferSize: 1, refCount: true })
Memory growth on WebSocketshareReplay({ refCount: false })connectable() and explicit teardown
Late subscriber see nothingshare() uses a plain SubjectshareReplay({ bufferSize: 1, refCount: true })
Socket reconnects on navigationshare() tears down at refCount 0connectable() with explicit .connect()
Two DOM listeners per eventfromEvent subscribed twiceshare() around it
Cache never clearsresetOnRefCountZero: false and stream endlessAdd takeUntil outside the share
Legacy publish()/multicast() warningsDeprecated RxJS 6 operatorsMigrate to share() and connectable()

Real-World Examples

1. Share one HTTP call

user$.pipe(share());

2. Cache the profile

profile$.pipe(shareReplay({ bufferSize: 1, refCount: true }));

3. Session socket

connectable(socket$).connect() at login;

4. Share a resize listener

fromEvent(window, 'resize').pipe(share());

5. Cache forever, explicit

share({ connector: () => new ReplaySubject(1), resetOnRefCountZero: false });

6. Cache until all leave

share({ connector: () => new ReplaySubject(1), resetOnRefCountZero: true });

7. Deprecated migration

// publish() + refCount() -> share()

8. Cache a timer

interval(1000).pipe(shareReplay({ bufferSize: 1, refCount: true }));

9. Share an expensive computation

heavyCompute$.pipe(share());

10. RefCount zero leak guard

source$.pipe(share(), takeUntil(destroy$)).subscribe(render);

Visual

Cold Against Hot

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ COLD: producer is created per subscription           โ”‚
โ”‚                                                      โ”‚
โ”‚   sub 1 โ”€โ”€โ–บ  begin โ”€โ”€โ–บ emit โ”€โ”€โ–บ complete             โ”‚
โ”‚   sub 2 โ”€โ”€โ–บ  begin โ”€โ”€โ–บ emit โ”€โ”€โ–บ complete             โ”‚
โ”‚   sub 3 โ”€โ”€โ–บ  begin โ”€โ”€โ–บ emit โ”€โ”€โ–บ complete             โ”‚
โ”‚                                                      โ”‚
โ”‚   3 executions, 3 timelines                          โ”‚
โ”‚                                                      โ”‚
โ”‚ HOT: producer exists independently                   โ”‚
โ”‚                                                      โ”‚
โ”‚   source โ”€โ”€โ–บ emit โ”€โ”€โ–บ emit โ”€โ”€โ–บ emit                  โ”‚
โ”‚     โ”‚  โ”œโ”€โ”€โ”€โ”€ sub 1                                   โ”‚
โ”‚     โ”‚  โ”œโ”€โ”€โ”€โ”€ sub 2                                   โ”‚
โ”‚     โ”‚  โ””โ”€โ”€โ”€โ”€ sub 3                                   โ”‚
โ”‚   1 execution, 3 deliveries                          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

share() Lifecycle

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  First subscriber  โ”€โ”€โ–บ refCount 1  โ”€โ”€โ–บ source starts โ”‚
โ”‚  Second subscriber โ”€โ”€โ–บ refCount 2  โ”€โ”€โ–บ source        โ”‚
โ”‚                        (no new subscription)         โ”‚
โ”‚                                                      โ”‚
โ”‚  One leaves        โ”€โ”€โ–บ refCount 1  โ”€โ”€โ–บ source stays  โ”‚
โ”‚  Both leave        โ”€โ”€โ–บ refCount 0  โ”€โ”€โ–บ source ends   โ”‚
โ”‚                                                      โ”‚
โ”‚  New subscriber    โ”€โ”€โ–บ refCount 1  โ”€โ”€โ–บ source starts โ”‚
โ”‚                        (a FRESH run, not a resume)   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

shareReplay vs share

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ A late subscriber AFTER the source emitted:          โ”‚
โ”‚                                                      โ”‚
โ”‚ share()          -> nothing (plain Subject)          โ”‚
โ”‚                                                      โ”‚
โ”‚ shareReplay(1)   -> the most recent value            โ”‚
โ”‚                                                      โ”‚
โ”‚ shareReplay(1,   -> the most recent value            โ”‚
โ”‚   refCount:true)    (buffer kept after refCount 0)   โ”‚
โ”‚                                                      โ”‚
โ”‚ shareReplay(1,   -> the most recent value            โ”‚
โ”‚   refCount:false)   (buffer kept FOREVER, no release)โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

connectable() Manual Control

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  subscribers attach       source not yet subscribed  โ”‚
โ”‚  โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€ sub 1                                  โ”‚
โ”‚          โ”œโ”€โ”€โ”€ sub 2                                  โ”‚
โ”‚          โ””โ”€โ”€โ”€ sub 3                                  โ”‚
โ”‚                                                      โ”‚
โ”‚  .connect()  โ”€โ”€โ–บ source subscription starts          โ”‚
โ”‚                                                      โ”‚
โ”‚  sub 1 leaves  โ”€โ”€โ–บ 2 remain  โ”€โ”€โ–บ source stays        โ”‚
โ”‚  sub 3 leaves  โ”€โ”€โ–บ 0 remain  โ”€โ”€โ–บ source stays        โ”‚
โ”‚                                                      โ”‚
โ”‚  .unsubscribe()  โ”€โ”€โ–บ source subscription stops       โ”‚
โ”‚                                                      โ”‚
โ”‚  no automatic teardown; the caller owns the handle   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Cold observableproducer created per subscription
Hot observableproducer exists independently of subscribers
share()multicast on first, unsubscribe on last, no cache
shareReplay({ refCount: true })multicast on first, unsubscribe on last, buffer kept
shareReplay({ refCount: false })multicast on first, never unsubscribe, buffer kept
connectable(source).connect()source starts on demand, stops on .unsubscribe()
ShareConfig default connector() => new Subject()
resetOnError defaulttrue
resetOnComplete defaultfalse
resetOnRefCountZero defaulttrue
Deprecated โ†’ modernpublish() + refCount() โ†’ share()
Deprecated โ†’ modernmulticast(() => new Subject()) โ†’ connectable()

Key takeaways:

  • Cold observables create their producer on subscribe; hot ones attach to an existing producer. http.get is cold; Subject and fromEvent are hot in the source sense; share() makes any cold source behave like a hot one.
  • share() is multicast without cache. The first subscriber starts the source, the last subscriber ends it, and every subscriber in between receives the same emissions. A late subscriber after refCount zero causes a fresh re-execution โ€” this is not a cache.
  • shareReplay({ refCount: true }) is the HTTP cache. The source runs once, the buffer retains the last value, and refCount zero tears down the source subscription (a no-op for a completed HTTP call) while keeping the buffer for future subscribers.
  • shareReplay({ refCount: false }) never unsubscribes. It is correct for a source that must outlive any subscriber and wrong for anything that closes โ€” a WebSocket, an interval, a DOM event listener. Prefer connectable() when you need that lifecycle under control.
  • connectable() gives you the source’s lifetime explicitly. Subscribers can come and go; the source starts on .connect() and stops on .unsubscribe(). Use it for sockets, session-lifetime resources, and any source whose lifecycle belongs to the application rather than to a component.
  • share({ connector, resetOnError, resetOnComplete, resetOnRefCountZero }) covers every case shareReplay covers, plus control over completion. The two flags that matter for caching are resetOnComplete: false and resetOnRefCountZero: false.
  • publish(), publishReplay(), publishLast(), multicast(), and refCount() are all deprecated. Migrate wholesale โ€” share() replaces the first pattern, shareReplay() replaces the second, connectable() replaces the third.

Remember: Multicasting changes who runs the work, not what the values are. Reach for share() when the source should run only while someone is listening; reach for shareReplay({ bufferSize: 1, refCount: true }) when the source should run once and be cached for later subscribers; reach for connectable() when the source must outlive individual subscribers. When the flame of shareReplay({ refCount: true }) still surprises you on a version boundary, share({ connector: () => new ReplaySubject(1), resetOnRefCountZero: false }) gives the same cache without the surprise. And whatever you choose, tear it down with takeUntil(destroy$) on the consumer side โ€” a multicast still leaks if its subscribers never unsubscribe.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!