| 1 |
import { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError'; |
| 2 |
import { Observable } from '../Observable'; |
| 3 |
import { OperatorFunction } from '../types'; |
| 4 |
import { filter } from './filter'; |
| 5 |
import { throwIfEmpty } from './throwIfEmpty'; |
| 6 |
import { defaultIfEmpty } from './defaultIfEmpty'; |
| 7 |
import { take } from './take'; |
| 8 |
|
| 9 |
/** |
| 10 |
* Emits the single value at the specified `index` in a sequence of emissions |
| 11 |
* from the source Observable. |
| 12 |
* |
| 13 |
* <span class="informal">Emits only the i-th value, then completes.</span> |
| 14 |
* |
| 15 |
*  |
| 16 |
* |
| 17 |
* `elementAt` returns an Observable that emits the item at the specified |
| 18 |
* `index` in the source Observable, or a default value if that `index` is out |
| 19 |
* of range and the `default` argument is provided. If the `default` argument is |
| 20 |
* not given and the `index` is out of range, the output Observable will emit an |
| 21 |
* `ArgumentOutOfRangeError` error. |
| 22 |
* |
| 23 |
* ## Example |
| 24 |
* |
| 25 |
* Emit only the third click event |
| 26 |
* |
| 27 |
* ```ts |
| 28 |
* import { fromEvent, elementAt } from 'rxjs'; |
| 29 |
* |
| 30 |
* const clicks = fromEvent(document, 'click'); |
| 31 |
* const result = clicks.pipe(elementAt(2)); |
| 32 |
* result.subscribe(x => console.log(x)); |
| 33 |
* |
| 34 |
* // Results in: |
| 35 |
* // click 1 = nothing |
| 36 |
* // click 2 = nothing |
| 37 |
* // click 3 = MouseEvent object logged to console |
| 38 |
* ``` |
| 39 |
* |
| 40 |
* @see {@link first} |
| 41 |
* @see {@link last} |
| 42 |
* @see {@link skip} |
| 43 |
* @see {@link single} |
| 44 |
* @see {@link take} |
| 45 |
* |
| 46 |
* @throws {ArgumentOutOfRangeError} When using `elementAt(i)`, it delivers an |
| 47 |
* `ArgumentOutOfRangeError` to the Observer's `error` callback if `i < 0` or the |
| 48 |
* Observable has completed before emitting the i-th `next` notification. |
| 49 |
* |
| 50 |
* @param index Is the number `i` for the i-th source emission that has happened |
| 51 |
* since the subscription, starting from the number `0`. |
| 52 |
* @param defaultValue The default value returned for missing indices. |
| 53 |
* @return A function that returns an Observable that emits a single item, if |
| 54 |
* it is found. Otherwise, it will emit the default value if given. If not, it |
| 55 |
* emits an error. |
| 56 |
*/ |
| 57 |
export function elementAt<T, D = T>(index: number, defaultValue?: D): OperatorFunction<T, T | D> { |
| 58 |
if (index < 0) { |
| 59 |
throw new ArgumentOutOfRangeError(); |
| 60 |
} |
| 61 |
const hasDefaultValue = arguments.length >= 2; |
| 62 |
return (source: Observable<T>) => |
| 63 |
source.pipe( |
| 64 |
filter((v, i) => i === index), |
| 65 |
take(1), |
| 66 |
hasDefaultValue ? defaultIfEmpty(defaultValue!) : throwIfEmpty(() => new ArgumentOutOfRangeError()) |
| 67 |
); |
| 68 |
} |