-10% with HALLOWEEN2021



RxJS: distinct explained

Posted by Tomasz Smykowski on

RxJS stands for Reactive Extensions for JavaScript. It is a great library to handle flow of items received by your application. Today you will learn what is one of the most commonly used RxJS operator: distinct.

The documentation explains it nicely. But what does it really mean? Let's forget about the documentation for a moment.

The analogy

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?

The example

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:

  1. 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
   .pipe(

      distinct(
         personStatus => personStatus.personName
      )

   )
   .subscribe(
      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.

Interesting facts

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.

Summary

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:

Part 1: RxJS throttle
Part 2: RxJS debounce
Part 3: RxJS filter
Part 4: RxJS distinctUntilChanged
Part 5: RxJS takeUntil
Part 6: RxJS map

 

0 comments

Leave a comment

Please note, comments must be approved before they are published