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.tsx206 chars7 lines
The output of the above example will be:
index.tsx10 chars6 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.tsx386 chars16 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