Skip to content

Function: defer()

defer<T>(factory): Stream<T>

Defined in: streams/defer.ts:17

Creates a stream that defers the creation of an inner stream until it is subscribed to.

This operator ensures that the factory function is called only when a consumer subscribes to the stream, making it a good choice for creating "cold" streams. Each new subscription will trigger a new call to the factory and create a fresh stream instance.

Type Parameters

T

T = any

The type of the values in the inner stream.

Parameters

factory

() => Stream<T> | Promise<T> | T[]

A function that returns the stream to be subscribed to.

Returns

Stream<T>

A new stream that defers subscription to the inner stream.

Examples

From defer.spec.ts:24

typescript
const emissions: any[] = [1, 2, 3];
const factory = jasmine
  .createSpy('factory')
  .and.callFake(() => mockStream(emissions, true));
const deferStream = defer(factory);
const collectedEmissions: number[] = [];
const subscription = deferStream.subscribe({
  next: (value: any) => collectedEmissions.push(value),
  complete: () => {
    expect(factory).toHaveBeenCalled();
    expect(collectedEmissions.length).toBe(3);
    expect(collectedEmissions).toEqual([1, 2, 3]);

    subscription.unsubscribe();
    done();
  },
  error: done.fail,
});

Released under the MIT License.