@reactivex/rxjs
Version:
Reactive Extensions for modern JavaScript
69 lines • 2.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var EmptyError_1 = require("../util/EmptyError");
var filter_1 = require("./filter");
var take_1 = require("./take");
var defaultIfEmpty_1 = require("./defaultIfEmpty");
var throwIfEmpty_1 = require("./throwIfEmpty");
var identity_1 = require("../util/identity");
/* tslint:enable:max-line-length */
/**
* Emits only the first value (or the first value that meets some condition)
* emitted by the source Observable.
*
* <span class="informal">Emits only the first value. Or emits only the first
* value that passes some test.</span>
*
* 
*
* If called with no arguments, `first` emits the first value of the source
* Observable, then completes. If called with a `predicate` function, `first`
* emits the first value of the source that matches the specified condition. It
* may also take a deprecated `resultSelector` function to produce the output
* value from the input value, and a `defaultValue` to emit in case the source
* completes before it is able to emit a valid value. Throws an error if
* `defaultValue` was not provided and a matching element is not found.
*
* ## Examples
* Emit only the first click that happens on the DOM
* ```ts
* import { fromEvent } from 'rxjs';
* import { first } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(first());
* result.subscribe(x => console.log(x));
* ```
*
* Emits the first click that happens on a DIV
* ```ts
* import { fromEvent } from 'rxjs';
* import { first } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(first(ev => ev.target.tagName === 'DIV'));
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link filter}
* @see {@link find}
* @see {@link take}
*
* @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
* callback if the Observable completes before any `next` notification was sent.
*
* @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]
* An optional function called with each item to test for condition matching.
* @param {R} [defaultValue] The default value emitted in case no valid value
* was found on the source.
* @return {Observable<T|R>} An Observable of the first item that matches the
* condition.
* @method first
* @owner Observable
*/
function first(predicate, defaultValue) {
var hasDefaultValue = arguments.length >= 2;
return function (source) { return source.pipe(predicate ? filter_1.filter(function (v, i) { return predicate(v, i, source); }) : identity_1.identity, take_1.take(1), hasDefaultValue ? defaultIfEmpty_1.defaultIfEmpty(defaultValue) : throwIfEmpty_1.throwIfEmpty(function () { return new EmptyError_1.EmptyError(); })); };
}
exports.first = first;
//# sourceMappingURL=first.js.map