The documentation offers an explanation how the operator works: "Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item".
But what does it really mean?
Imagine your scouts come from the battlefield to give you information how the war zone looks like. However, reports duplicate. So sometimes you receive multiple reports with exactly the same information. To avoid it, you order your war advisor to review each report, and contact you only, if the latest report changed from the previous one. That way you save some precious time.
This is how RxJS distinctUntilChanged works. It looks like this:
Balls represent items coming to a filter operator. distinctUntilChanged operator checks if an item is different from the previous one. The first ball is emitted. However, since the second ball is also red - it is kicked out. The third ball is pink. Because it is different from the previous ball it is emitted.
How to translate this analogy to programming? Why an app should ignore repetitive items?
RxJS distinctUntilChanged is useful when you want to ignore repetitive items. As usual, you could do it on your own by storing a previous item in the subscription method, and comparing it to the current one. However, distinctUntilChanged does it for you in the pipe. That way your subscription method won't have to deal with it.
Let's say you wrote an app that tracks a price of a graphics card you really like. App checks the price each hour to make sure you won't miss the best deal. However, you notice the price does not drop for days. But still you receive a price notification every hour. With distinctUntilChanged you will make sure to receive notification only when the price changes.
The logic you want to introduce looks like this:
When the time to check the price arrived:
- check if the new price is different from the previous one
- notify user if it is true
The formal way to write it down with RxJS like this:
reading => sendGPUPriceChangeNotification(reading)
As you can see it is pretty complex syntax. It is because RxJS offers more operators than distinctUntilChanged and ways to combine them. You can think of pipe section as a decision-making how to handle incoming events, and subscribe what to do with events that pipe returns.
There are other operators you can use in the pipe section. However, there are two interesting things about distinctUntilChanged I want to share with you before this article finishes.
- You can also use an additional, optional parameter called compare. It is a handy optional comparison function to distinguish items differently than with an equality check.
- There is also an optional parameter called keySelector. The parameter is your friend, if you want to compare objects by their properties, say "id".
Also check out: