Skip to content

Function: tap()

tap<T>(tapFunction): Operator<T, T>

Defined in: operators/tap.ts:19

Creates a stream operator that performs a side-effect for each value from the source stream without modifying the value.

This operator is primarily used for debugging, logging, or other non-intrusive actions that need to be performed on each value as it passes through the pipeline. It is completely transparent to the data stream itself, as it does not transform, filter, or buffer the values. The provided tapFunction is executed for each value before the value is emitted to the next operator.

Type Parameters

T

T = any

The type of the values in the source and output streams.

Parameters

tapFunction

(value) => any

The function to perform the side-effect. It receives the value from the stream and can be synchronous or asynchronous.

Returns

Operator<T, T>

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

Examples

From tap.spec.ts:4

typescript
const testStream = from([1, 2, 3]);
const sideEffectFn = jasmine.createSpy('sideEffectFn');
const tappedStream = testStream.pipe(
  startWith(0),
  endWith(4),
  tap(sideEffectFn),
  catchError(console.log),
  finalize(() => {})
);
let results: any[] = [];
tappedStream.subscribe({
  next: (value) => results.push(value),
  complete: () => {
    expect(sideEffectFn).toHaveBeenCalledTimes(5);

    expect(sideEffectFn).toHaveBeenCalledWith(0);
    expect(sideEffectFn).toHaveBeenCalledWith(1);
    expect(sideEffectFn).toHaveBeenCalledWith(2);
    expect(sideEffectFn).toHaveBeenCalledWith(3);
    expect(sideEffectFn).toHaveBeenCalledWith(4);

    expect(results).toEqual([0, 1, 2, 3, 4]);

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

Released under the MIT License.