how to use the distinctuntilchanged function from the rxjs library in javascript

distinctUntilChanged() is an RxJS operator that will omit emissions that are the same as the previous emission. It is commonly used when you are applying transformations to an observable sequence that could potentially produce the same output multiple times.

Here's an example of how to use distinctUntilChanged() to filter out consecutive duplicate values in an observable stream:

index.tsx
import { from } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';

const source$ = from([1, 2, 2, 3, 3, 3, 4, 5, 5]);

source$.pipe(distinctUntilChanged()).subscribe(x => console.log(x));
206 chars
7 lines

The output of the above example will be:

index.tsx
1
2
3
4
5
10 chars
6 lines

In this example, the from() function creates an observable sequence from an array of numbers. We then use the pipe() method to apply the distinctUntilChanged() operator to the stream.

As a result, only the distinct values will be emitted to the console, and any consecutive duplicates will be filtered out.

You can also pass in a function as an argument to distinctUntilChanged() if you need to compare objects based on their properties rather than their references:

index.tsx
import { from } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';

const source$ = from([
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 }
]);

const compareFunction = (prev, curr) => prev.name === curr.name;

source$
  .pipe(distinctUntilChanged(compareFunction))
  .subscribe(x => console.log(x));
386 chars
16 lines

In this example, we are comparing objects based on their name property only, rather than their entire reference. As a result, only the objects with distinct names will be emitted to the console, and any other consecutive duplicates will be filtered out.

gistlibby LogSnag