Skip to content

Function: defaultIfEmpty()

defaultIfEmpty<T>(defaultValue): Operator<T, T>

Defined in: operators/defaultIfEmpty.ts:15

Creates a stream operator that emits a default value if the source stream is empty.

This operator monitors the source stream for any emitted values. If the source stream completes without emitting any values, this operator will emit a single defaultValue and then complete. If the source stream does emit at least one value, this operator will pass all values through and will not emit the defaultValue.

Type Parameters

T

T = any

The type of the values in the stream.

Parameters

defaultValue

T

The value to emit if the source stream is empty.

Returns

Operator<T, T>

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

Examples

From defaultIfEmpty.spec.ts:4

typescript
const stream = createSubject();
const defaultValue = 'Default Value';
const processedStream = stream.pipe(defaultIfEmpty(defaultValue));
const emittedValues: any[] = [];
processedStream.subscribe({
  next: (value) => emittedValues.push(value),
  complete: () => {
    expect(emittedValues).toEqual([defaultValue]);
    done();
  },
});
stream.complete();

Released under the MIT License.