UNPKG

1.96 kBPlain TextView Raw
1
2import { Observable } from 'rxjs';
3import { elementAt as higherOrder } from 'rxjs/operators';
4
5/**
6 * Emits the single value at the specified `index` in a sequence of emissions
7 * from the source Observable.
8 *
9 * <span class="informal">Emits only the i-th value, then completes.</span>
10 *
11 * <img src="./img/elementAt.png" width="100%">
12 *
13 * `elementAt` returns an Observable that emits the item at the specified
14 * `index` in the source Observable, or a default value if that `index` is out
15 * of range and the `default` argument is provided. If the `default` argument is
16 * not given and the `index` is out of range, the output Observable will emit an
17 * `ArgumentOutOfRangeError` error.
18 *
19 * @example <caption>Emit only the third click event</caption>
20 * var clicks = Rx.Observable.fromEvent(document, 'click');
21 * var result = clicks.elementAt(2);
22 * result.subscribe(x => console.log(x));
23 *
24 * // Results in:
25 * // click 1 = nothing
26 * // click 2 = nothing
27 * // click 3 = MouseEvent object logged to console
28 *
29 * @see {@link first}
30 * @see {@link last}
31 * @see {@link skip}
32 * @see {@link single}
33 * @see {@link take}
34 *
35 * @throws {ArgumentOutOfRangeError} When using `elementAt(i)`, it delivers an
36 * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0` or the
37 * Observable has completed before emitting the i-th `next` notification.
38 *
39 * @param {number} index Is the number `i` for the i-th source emission that has
40 * happened since the subscription, starting from the number `0`.
41 * @param {T} [defaultValue] The default value returned for missing indices.
42 * @return {Observable} An Observable that emits a single item, if it is found.
43 * Otherwise, will emit the default value if given. If not, then emits an error.
44 * @method elementAt
45 * @owner Observable
46 */
47export function elementAt<T>(this: Observable<T>, index: number, defaultValue?: T): Observable<T> {
48 return higherOrder.apply(undefined, arguments)(this);
49}