distinctUntilChanged – RxJS

distinctUntilChanged is a very useful RxJS operator that comes in handy when you need to make sure that your observable emits value only when the current value it is about to emit is different from the last emitted value.

Let’s understand this in detail using following example;

import { from } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';

from([1, 2, 3, 3, 3, 3, 3, 3, 4, 5, 5])
  .subscribe(num => console.log(num));
// output: 1, 2, 3, 4, 5

Although values 3 and 5 appears multiple times in the above code, these values will be logged only once as the distinctUntilChanged operator will emit the values for first time and will discard the duplicate ones.

Let’s consider one more example;

import { from } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';

const cities = [
  { name: 'Pune', country: 'India' },
  { name: 'Hyderabad', country: 'India' },
  { name: 'Pokhara', country: 'Nepal' },
  { name: 'Kathmandu', country: 'Nepal' }

  distinctUntilChanged((prevCity, nextCity) => prevCity.country === nextCity.country)
.subscribe(city => console.log(city));
// output:
// { name: 'Pune', country: 'India' }
// { name: 'Pokhara', country: 'Nepal' }

Above code will skip Hyderabad and Kathmandu since there is no change between previous object’s country and current object’s country.

Must Read: delay – RxJS

RxJS Operators – delay

The delay operator in RxJS delays the emitted value by specified time.

Consider the following example. The name$ observable will produce output almost instantaneously without any delay.

const name$ = of('Harshal');
name$.subscribe(name => console.log(name));

To add a delay to the above observable we need to first import the delay operator.

import { delay } from 'rxjs/operators';

Next we need to add pipe to Observable to consume the delay operator.

const name$ = of('Harshal').pipe(delay(4000));
name$.subscribe(name => console.log(name));

This will add a delay of 4000 milliseconds i.e 4 seconds to the name$ observable.

You can also pass Date to delay operator.

const date = new Date('Dec 31 2050 23:59:59')
const message$ = of('Happy New Year!').pipe(delay(date));
message$.subscribe(name => console.log(name));

In the above example, the value within the message$ observable will be emitted only after the specified date.