Debian Codegraph @

node/rxjs/src/internal/operators/take.ts

raw
1 import { MonoTypeOperatorFunction } from '../types';
2 import { EMPTY } from '../observable/empty';
3 import { operate } from '../util/lift';
4 import { createOperatorSubscriber } from './OperatorSubscriber';
5
6 /**
7 * Emits only the first `count` values emitted by the source Observable.
8 *
9 * <span class="informal">Takes the first `count` values from the source, then
10 * completes.</span>
11 *
12 * ![](take.png)
13 *
14 * `take` returns an Observable that emits only the first `count` values emitted
15 * by the source Observable. If the source emits fewer than `count` values then
16 * all of its values are emitted. After that, it completes, regardless if the
17 * source completes.
18 *
19 * ## Example
20 *
21 * Take the first 5 seconds of an infinite 1-second interval Observable
22 *
23 * ```ts
24 * import { interval, take } from 'rxjs';
25 *
26 * const intervalCount = interval(1000);
27 * const takeFive = intervalCount.pipe(take(5));
28 * takeFive.subscribe(x => console.log(x));
29 *
30 * // Logs:
31 * // 0
32 * // 1
33 * // 2
34 * // 3
35 * // 4
36 * ```
37 *
38 * @see {@link takeLast}
39 * @see {@link takeUntil}
40 * @see {@link takeWhile}
41 * @see {@link skip}
42 *
43 * @param count The maximum number of `next` values to emit.
44 * @return A function that returns an Observable that emits only the first
45 * `count` values emitted by the source Observable, or all of the values from
46 * the source if the source emits fewer than `count` values.
47 */
48 export function take<T>(count: number): MonoTypeOperatorFunction<T> {
49 return count <= 0
50 ? // If we are taking no values, that's empty.
51 () => EMPTY
52 : operate((source, subscriber) => {
53 let seen = 0;
54 source.subscribe(
55 createOperatorSubscriber(subscriber, (value) => {
56 // Increment the number of values we have seen,
57 // then check it against the allowed count to see
58 // if we are still letting values through.
59 if (++seen <= count) {
60 subscriber.next(value);
61 // If we have met or passed our allowed count,
62 // we need to complete. We have to do <= here,
63 // because re-entrant code will increment `seen` twice.
64 if (count <= seen) {
65 subscriber.complete();
66 }
67 }
68 })
69 );
70 });
71 }