Skip to content

take

Takes only the first n emissions from the source observable, then completes. It completes in the same update as the nth emission, after passing that value on. The initial value is passed on and not counted.

Timeline of observable events1234
take(3)
Timeline of observable events123
// Timeline:
//
// num$ 1 2 3 4 (ignored)
// taken$ 1 2 3|(completes)
//
// Explanation:
// - take emits only the first n values, completing with the nth
// - Subsequent emissions from the source are ignored
const num$ = source<number>();
const taken$ = num$.pipe(take(3));
const valueHistory: number[] = [];
taken$.subscribe((x) => {
valueHistory.push(x);
});
num$.next(1);
num$.next(2);
num$.next(3);
assert.deepStrictEqual(valueHistory, [1, 2, 3]);
assert.isTrue(taken$.isCompleted);
num$.next(4); // ignored (already completed)
assert.deepStrictEqual(valueHistory, [1, 2, 3]);

View source on GitHub