24 Jul 2024
5 min

filter – RxJS Reference

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:

  1. Subscribe to a source observable
  2. When a new value arrives from a source observable, execute the predicate function for the current value
  3. If the function returns `false, ignore the value, otherwise, send the value to the observer
  4. Once the source observable completes, send the complete notification to the observer
  5. 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);

Playground

Additional resources

See also

Frequently asked questions

How do I filter values in an RxJS observable?

Use the filter() operator inside pipe(), passing a predicate function that returns true for values you want to emit and false for values to drop. The predicate runs once for each value the source observable emits, and only values returning true reach the subscriber. The approach works like the standard Array.filter method, but applied to a stream over time. Predicates can also use the optional index argument, which counts emitted values from 0 since subscription.

What is the difference between filter and distinctUntilChanged in RxJS?

filter() decides whether each value is emitted based on a predicate you write, while distinctUntilChanged() drops a value only when it matches the previous emitted value. Use filter() for conditions such as value > 10 or event.target.tagName === 'DIV', and use distinctUntilChanged() when you only want to suppress consecutive duplicates. The two operators solve different problems and are often combined in the same pipe.

What is the difference between filter and takeWhile in RxJS?

filter() skips values that fail the predicate and keeps the subscription alive, so later values can still be emitted. takeWhile() emits values while the condition holds and completes the observable as soon as the condition fails. Choose filter() when non-matching values should simply be ignored, and takeWhile() when the stream should end once a condition stops being true.

How do I filter click events by target element type with RxJS fromEvent?

Pipe fromEvent(document, 'click') through filter() and check event.target.tagName in the predicate. Only clicks whose target is a DIV reach the subscriber, while clicks on other elements such as a SPAN are silently ignored. Attaching one listener to document and filtering in the stream is more efficient than adding a listener to every element, which is the approach the article demonstrates.

How does the RxJS filter operator handle completion and errors?

The filter() operator forwards the source's lifecycle notifications unchanged. When the source observable completes, filter() sends the complete notification to the observer, and if the source throws an error, that error is passed on as well. Predicate results only control which next values are emitted, so a filter that rejects every value still completes normally when the source completes.

Share this post

Sign up for our newsletter

Stay up-to-date with the trends and be a part of a thriving community.