Emits only the first value (or the first value that meets some condition)
emitted by the source Observable.
first<T, D>(predicate?: ((value: T, index: number, source: Observable<T>) => boolean) | null, defaultValue?: D): OperatorFunction<T, T | D>
Parameters
predicate |
Optional. Default is undefined .
An optional function called with each item to test for condition matching.
|
defaultValue |
Optional. Default is undefined .
The default value emitted in case no valid value
was found on the source.
|
Returns
OperatorFunction<T, T | D>
: An Observable of the first item that matches the
condition.
Throws
EmptyError
Delivers an EmptyError to the Observer's error
callback if the Observable completes before any next
notification was sent.
Description
Emits only the first value. Or emits only the first
value that passes some test.
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
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
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));
Overloads
first(predicate?: null, defaultValue?: D): OperatorFunction<T, T | D>
Parameters
predicate |
Optional. Default is undefined .
Type: null .
|
defaultValue |
Optional. Default is undefined .
Type: D .
|
Returns
OperatorFunction<T, T | D>
|
first(predicate: (value: T, index: number, source: Observable<T>) => value is S, defaultValue?: S): OperatorFunction<T, S>
Parameters
predicate |
Type: (value: T, index: number, source: Observable) => value is S .
|
defaultValue |
Optional. Default is undefined .
Type: S .
|
Returns
OperatorFunction<T, S>
|
first(predicate: (value: T, index: number, source: Observable<T>) => boolean, defaultValue?: D): OperatorFunction<T, T | D>
Parameters
predicate |
Type: (value: T, index: number, source: Observable) => boolean .
|
defaultValue |
Optional. Default is undefined .
Type: D .
|
Returns
OperatorFunction<T, T | D>
|