The documentation explains it nicely. But what does it really mean? Let's forget about the documentation for a moment.
Imagine you are a collector of rare artifacts. You keep ones that you don't already own, but throw away items that you possess. This is how distinct works.
It looks like this:
How to translate this analogy to programming? Why an app should ignore non-unique items?
Let's say there is a WebSocket that sends information about online status of team members. The endpoint however sends the status multiple times per each member. However, you'd like to display a list with statuses of each of them with the first reading about every one person.
The logic you want to introduce to your app looks like this:
- When a new WebSocket message arrives:
- if I have status of that person: ignore message
- otherwise display the status on a list
The formal way to write it down with RxJS like this:
personStatus => personStatus.personName
personStatus => addToList(personStatus);
As you can see it is pretty complex syntax. It is because RxJS offers more operators than map 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 the distinct I want to share with you before this article finishes.
Distinct operator accepts an optional keySelector function. It was actually used in the example above. It is used to indicate by what key you want to compare items.
There is also another optional parameter called flushes. You can pass an observable to it. Whenever an item will be sent to that observable, internal memory about items that arrived before from the main pipe will be cleared, so that distinct starts to allow new items, even if they occurred before the flush.
Distinct operator is a useful RxJS operator when you want to ignore duplicated items that can occur any time. Remember about it, if you like to make sure there will only one item of a given kind.
Also check out: