DEV Community

Sabyasachi D Maven
Sabyasachi D Maven

Posted on

RxJS Operators: distinctUntilChanged & distinctUntilKeyChanged

Alt Text

As per the official doc, RxJS is a library for composing asynchronous and event-based programs by using observable sequences.

While performing the input search by keyword, we generally use the distinctUntilChanged operator.

Today, we will try to explore both of the rxjs operators.

Going by the official definition:
distinctUntilChanged: It returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.

The sequence diagram for the distinctUntilChanged is attached below:

Alt Text

If we have a look at the compare function, it compares the distinct item from previous item from the source.

Also, we skip the compare function, it does the equality check by default. (applies to distinctUntilChanged && distinctUntilKeyChanged)

If we are trying to compare for the primitive values, we will consider the distinctUntilChanged operator. See the example below:

Alt Text

Now, let's try to do some variations with the custom objects.

Alt Text

If we see the example, we are trying to compare with "username" property, if it's distinct, we will take the value, otherwise it will be skipped.

Alt Text

Let's move on to the different flavor, which is distinctUntilKeyChanged

distinctUntilKeyChanged: Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item, using a property accessed by using the key provided to check if the two items are distinct.

The sequence diagram for the distinctUntilKeyChanged is attached below:

Alt Text

If we have a look at the compare function, it compares the distinct item from previous item from the source.

Alt Text

If we see the example, we are trying to compare with "username" property. But, here we trying to just pass the key directly and get the same output. Here, we write less code. If it's distinct, we will take the value, otherwise it will be skipped.

Alt Text

If, we want to try out more examples, we can try to play-around with the code.

We can use these two operators based on the usage. But, common is the input search keyword.

I hope this article have given some sense about the RxJS operators.
Happy coding. Keep learning. Keep exploring. 😊

Top comments (0)