Skip to content

Function: finalize()

finalize<T>(callback): Operator<T, T>

Defined in: hooks/finalize.ts:16

Creates a stream operator that invokes a finalizer callback upon stream termination.

This operator is useful for performing cleanup tasks, such as closing resources or logging, after a stream has completed or encountered an error. The provided callback is guaranteed to be called exactly once, regardless of whether the stream terminates gracefully or with an error.

Type Parameters

T

T = any

The type of the values emitted by the stream.

Parameters

callback

() => any

The function to be called when the stream completes or errors. It can be synchronous or return a Promise.

Returns

Operator<T, T>

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

Examples

From finalize.spec.ts:5

typescript
const called: string[] = [];
const stream = createStream('test', async function* () {
  yield 1;
  yield 2;
  yield 3;
});
const finalStream = stream.pipe(
  finalize(() => {
    called.push('finalized');
  })
);
const values: number[] = [];
finalStream.subscribe({
  next: (v: number) => values.push(v),
  complete: () => {
    expect(values).toEqual([1, 2, 3]);
    expect(called).toEqual(['finalized']);
    done();
  },
});

Released under the MIT License.