Observable: first() method
Observable API
Observable API
The first() method of the Observable interface returns a promise that fulfills with the first value emitted by the source observable.
Syntax
first()
first(options)
Parameters
options- : An options object containing the following properties:
signal- : An AbortSignal that can be used to cancel the operation. Aborting the signal unsubscribes from the source and rejects the promise with the signal's reason. If the signal is already aborted, the promise rejects without subscribing to the source.
Return value
A Promise that resolves to the first value emitted by the source observable. If the source completes without emitting any values, the promise rejects with a RangeError.
If the source errors, the promise rejects with that error. If the operation is aborted, the promise rejects with the abort reason.
Description
Like other promise-returning operators, this method subscribes to the source immediately when called. It does not require a separate call to subscribe().
As soon as the source emits a value, first() unsubscribes from it without waiting for it to complete. If the source never emits a value or completes, the promise remains pending unless the operation errors or is aborted.
If the selected value is a promise, the returned promise adopts its eventual state rather than fulfilling with the promise object itself.
Examples
Using first()
This example displays the coordinates of the first button click, then stops listening. Click Restart after the stream ends to try again.
```html hidden live-sample___basic-first
Waiting for clicks
```js live-sample___basic-first
const btn = document.querySelector("button");
const output = document.querySelector("p");
const restart = document.querySelector("#restart");
function start() {
restart.disabled = true;
output.textContent = "Waiting for clicks";
btn
.when("click")
.first()
.then((result) => {
restart.disabled = false;
output.textContent = `${result.clientX},${result.clientY}`;
});
}
restart.when("click").subscribe(start);
start();
Specifications
Browser compatibility
See also
- Observable.last()
- Observable.find()
- Using observables
- Observable explainer