1 import { Operator } from '../Operator';
2 import { Subscriber } from '../Subscriber';
3 import { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError';
4 import { empty } from '../observable/empty';
5 import { Observable } from '../Observable';
6 import { MonoTypeOperatorFunction, TeardownLogic } from '../types';
9 * Emits only the first `count` values emitted by the source Observable.
11 * <span class="informal">Takes the first `count` values from the source, then
16 * `take` returns an Observable that emits only the first `count` values emitted
17 * by the source Observable. If the source emits fewer than `count` values then
18 * all of its values are emitted. After that, it completes, regardless if the
22 * Take the first 5 seconds of an infinite 1-second interval Observable
24 * import { interval } from 'rxjs';
25 * import { take } from 'rxjs/operators';
27 * const intervalCount = interval(1000);
28 * const takeFive = intervalCount.pipe(take(5));
29 * takeFive.subscribe(x => console.log(x));
39 * @see {@link takeLast}
40 * @see {@link takeUntil}
41 * @see {@link takeWhile}
44 * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an
45 * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
47 * @param {number} count The maximum number of `next` values to emit.
48 * @return {Observable<T>} An Observable that emits only the first `count`
49 * values emitted by the source Observable, or all of the values from the source
50 * if the source emits fewer than `count` values.
54 export function take<T>(count: number): MonoTypeOperatorFunction<T> {
55 return (source: Observable<T>) => {
59 return source.lift(new TakeOperator(count));
64 class TakeOperator<T> implements Operator<T, T> {
65 constructor(private total: number) {
67 throw new ArgumentOutOfRangeError;
71 call(subscriber: Subscriber<T>, source: any): TeardownLogic {
72 return source.subscribe(new TakeSubscriber(subscriber, this.total));
77 * We need this JSDoc comment for affecting ESDoc.
81 class TakeSubscriber<T> extends Subscriber<T> {
82 private count: number = 0;
84 constructor(destination: Subscriber<T>, private total: number) {
88 protected _next(value: T): void {
89 const total = this.total;
90 const count = ++this.count;
92 this.destination.next(value);
93 if (count === total) {
94 this.destination.complete();