Demo: first
The first is a filter operator that emits only the first value or the first value matching the optional condition, when specified.
first(); //Without any condition
first(v => optionalCondition);
It throws an EmptyError if no match is found as the source completes. find operator is similar but, does not throw any error for no match.
//Emit every 1sec starting at .5 sec
const source = timer(500, 1000);
//take only the first item satisfying the given condition
const emitFirstMatch = first(v => v>=4);
const output = source.pipe(emitFirstMatch).subscribe(v=>console.log(v))
What is happening ?
The operators first and last can filter both:
- By position as well as by condition.
The first operator without a condition parameter is like take(1):
- It will take only the first item from source and add a complete notification.
Secondly, the first operator can also take a boolean condition.
- Where it will emit the first matching source item and add complete.
But, importantly, if the operator could not find a match to emit:
- It will throw an "EmptyError" when the source completes.
- In case we do not want an "Errro" for no match, we can use the "find" operator instead.
Coming to our demo, the source is supposed to emit an infinite number of items.
- But, as we are interested only on the first value which is (greater than or equals to 4).
- We have piped in our source into the first operator with the desired condition as shown.
- For this, we will only get the first matching value 4, in our output.