Skip to content

Function: shareReplay()

shareReplay<T>(bufferSize): Operator<T, T>

Defined in: operators/shareReplay.ts:22

Creates a stream operator that shares a single subscription to the source stream and replays a specified number of past values to new subscribers.

This operator multicasts the source stream, ensuring that multiple downstream consumers can receive values from a single source connection. It uses an internal ReplaySubject to cache the most recent values. When a new consumer subscribes, it immediately receives these cached values before receiving new ones.

This is useful for:

  • Preventing redundant execution of a source stream (e.g., a network request).
  • Providing a "state history" to late subscribers.

Type Parameters

T

T = any

The type of the values in the stream.

Parameters

bufferSize

number = Infinity

The number of last values to replay to new subscribers. Defaults to Infinity.

Returns

Operator<T, T>

An Operator instance that can be used in a stream's pipe method.

Examples

From shareReplay.spec.ts:4

typescript
let executionCount = 0;
const source = createStream<number>('source', async function* () {
  executionCount++;
  yield 42;
});
const shared$ = source.pipe(shareReplay());
const values1: number[] = [];
const values2: number[] = [];
shared$.subscribe({
  next: (val) => values1.push(val),
  complete: () => {
    // Second subscription after complete
    shared$.subscribe({
      next: (val) => values2.push(val),
      complete: () => {
        expect(values1).toEqual([42]);
        expect(values2).toEqual([42]);
        expect(executionCount).toBe(1);
        done();
      },
      error: done.fail,
    });
  },
  error: done.fail,
});

Released under the MIT License.