Skip to content

Function: take()

take<T>(count): Operator<T, T>

Defined in: operators/take.ts:17

Creates a stream operator that emits only the first count values from the source stream and then completes.

This operator is a powerful tool for controlling the length of a stream. It consumes values from the source one by one, and as long as the total number of values emitted is less than count, it passes them through to the output. Once the count is reached, it stops processing the source and signals completion to its downstream consumers. This is especially useful for managing finite segments of large or infinite streams.

Type Parameters

T

T = any

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

Parameters

count

number

The maximum number of values to take from the beginning of the stream.

Returns

Operator<T, T>

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

Examples

From take.spec.ts:4

typescript
const testStream = from([1, 2, 3, 4, 5]);
const count = 3;
const takenStream = testStream.pipe(take(count));
let results: any[] = [];
takenStream.subscribe({
  next: (value) => results.push(value),
  complete: () => {
    expect(results).toEqual([1, 2, 3]); // Should emit only the first three values
    done();
  },
});

Released under the MIT License.