filter
filter
emits all items received from the source observable that satisfy a specified comparison function known as the predicate. The idea is very similar to the standard filter method on Array
.
The predicate is passed as a parameter and is executed for each value emitted by the source observable. If it returns true
, the value is emitted, if false
the value is ignored and not passed to the observer. The function also gest index
parameter which is the counterer of values that have been emitted by the source observable since the subscription, starting from the number 0
.
If you just need to filter out consecutive similar values, you can use distinctUntilChanged. When you need to complete an observable if a condition fails use takeWhile!
filter
operator works in the following way:
- Subscribe to a source observable
- When a new value arrives from a source observable, execute the predicate function for the current value
- If the function returns `false, ignore the value, otherwise, send the value to the observer
- Once the source observable completes, send the complete notification to the observer
- If the source observable throws an error, send the error notification to the observer
Usage
filter
quite often used in everyday development to filter out some values. For example, you only need to listen for the click
event on DIV
elements. For the efficiency, you add an event listener to the document
and simply ignore DOM nodes that aren’t DIV
. Here’s how you can do it:
const div = document.createElement('div');
const span = document.createElement('span');
document.body.appendChild(div);
document.body.appendChild(span);
fromEvent(document, 'click').pipe(
filter((event: any) => event.target.tagName === 'DIV')
).subscribe(event => console.log(event));
setTimeout(() => div.click(), 1000);
// this click event is filtered out and not emitted to the observer
setTimeout(() => span.click(), 2000);