Learn RxJS
  • Introduction
  • Learn RxJS
    • Operators
      • Combination
        • combineAll
        • combineLatest
        • concat
        • concatAll
        • endWith
        • forkJoin
        • merge
        • mergeAll
        • pairwise
        • race
        • startWith
        • withLatestFrom
        • zip
      • Conditional
        • defaultIfEmpty
        • every
        • iif
        • sequenceEqual
      • Creation
        • ajax
        • create
        • defer
        • empty
        • from
        • fromEvent
        • generate
        • interval
        • of
        • range
        • throw
        • timer
      • Error Handling
        • catch / catchError
        • retry
        • retryWhen
      • Multicasting
        • publish
        • multicast
        • share
        • shareReplay
      • Filtering
        • audit
        • auditTime
        • debounce
        • debounceTime
        • distinct
        • distinctUntilChanged
        • distinctUntilKeyChanged
        • filter
        • find
        • first
        • ignoreElements
        • last
        • sample
        • single
        • skip
        • skipUntil
        • skipWhile
        • take
        • takeLast
        • takeUntil
        • takeWhile
        • throttle
        • throttleTime
      • Transformation
        • buffer
        • bufferCount
        • bufferTime
        • bufferToggle
        • bufferWhen
        • concatMap
        • concatMapTo
        • exhaustMap
        • expand
        • groupBy
        • map
        • mapTo
        • mergeMap / flatMap
        • mergeScan
        • partition
        • pluck
        • reduce
        • scan
        • switchMap
        • switchMapTo
        • toArray
        • window
        • windowCount
        • windowTime
        • windowToggle
        • windowWhen
      • Utility
        • tap / do
        • delay
        • delayWhen
        • dematerialize
        • finalize / finally
        • let
        • repeat
        • timeInterval
        • timeout
        • timeoutWith
        • toPromise
      • Full Listing
    • Subjects
      • AsyncSubject
      • BehaviorSubject
      • ReplaySubject
      • Subject
    • Recipes
      • Alphabet Invasion Game
      • Battleship Game
      • Breakout Game
      • Car Racing Game
      • Catch The Dot Game
      • Click Ninja Game
      • Flappy Bird Game
      • Game Loop
      • Horizontal Scroll Indicator
      • Http Polling
      • Lockscreen
      • Matrix Digital Rain
      • Memory Game
      • Mine Sweeper Game
      • Platform Jumper Game
      • Progress Bar
      • Save Indicator
      • Smart Counter
      • Space Invaders Game
      • Stop Watch
      • Swipe To Refresh
      • Tank Battle Game
      • Tetris Game
      • Type Ahead
      • Uncover Image Game
    • Concepts
      • RxJS Primer
      • Get started transforming streams with map, pluck, and mapTo
      • Time based operators comparison
      • RxJS v5 -> v6 Upgrade
Powered by GitBook
On this page
  • Only emit when the current value is different than the last.
  • Why use distinctUntilChanged?
  • Examples
  • Related Recipes
  • Additional Resources
  1. Learn RxJS
  2. Operators
  3. Filtering

distinctUntilChanged

PreviousdistinctNextdistinctUntilKeyChanged

Last updated 1 year ago

signature: distinctUntilChanged(compare: function): Observable

Only emit when the current value is different than the last.


💡 distinctUntilChanged uses === comparison by default, object references must match!

💡 If you want to compare based on an object property, you can use distinctUntilKeyChanged instead!


Why use distinctUntilChanged?

This operator stands guard, ensuring that you're not bombarded with repetitive information. Imagine if your best friend kept repeating the same story to you every time you met. It'd get old, right? The distinctUntilChanged operator does just that; it prevents subsequent identical emissions from an observable.

Think about a search bar on a website. As users type their queries, you don't want to send a server request for the same input value multiple times in a row, it would be redundant and inefficient. Here’s where distinctUntilChanged combined with debounceTime could shine. Imagine a user typing in a search term and then slightly hesitating before adding another letter. You might want to wait just a little bit (that’s (debounceTime)[debouncetime.md] doing its magic) and then, before firing off a request, ensure the term is actually different than the previous one - this is where you can utilize distinctUntilChanged.

For example, if a user is searching for "apple" and they type "app" -> wait a bit -> "appl" -> backtrack to "app" -> type again "appl", without distinctUntilChanged, you might end up sending redundant requests. But with it, once "appl" is recognized as previously processed, it won't send the redundant search request again.

It's important to remember that distinctUntilChanged compares the current value with the last emitted value. It doesn’t keep a long history. So, if an observable emitted the values 1, 2, 2, 3, 3, 2 - you’d get 1, 2, 3, 2 in return. By default, it also uses simple equality to compare values. If you're working with objects or arrays, you might need to provide a custom comparison function to determine whether values are distinct.

In essence, when you're looking to filter out consecutive duplicate emissions from your observables, think of distinctUntilChanged as your go-to option.

Examples

Example 1: distinctUntilChanged with basic values

( StackBlitz )

// RxJS v6+
import { from } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';

// only output distinct values, based on the last emitted value
const source$ = from([1, 1, 2, 2, 3, 3]);

source$
  .pipe(distinctUntilChanged())
  // output: 1,2,3
  .subscribe(console.log);

Example 2: distinctUntilChanged with objects

( StackBlitz )

// RxJS v6+
import { from } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';

const sampleObject = { name: 'Test' };

//Objects must be same reference
const source$ = from([sampleObject, sampleObject, sampleObject]);

// only emit distinct objects, based on last emitted value
source$
  .pipe(distinctUntilChanged())
  // output: {name: 'Test'}
  .subscribe(console.log);

Example 3: Using custom comparer function

( StackBlitz )

// RxJS v6+
import { from } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';

// only output distinct values, based on the last emitted value
const source$ = from([
  { name: 'Brian' },
  { name: 'Joe' },
  { name: 'Joe' },
  { name: 'Sue' }
]);

source$
  // custom compare for name
  .pipe(distinctUntilChanged((prev, curr) => prev.name === curr.name))
  // output: { name: 'Brian }, { name: 'Joe' }, { name: 'Sue' }
  .subscribe(console.log);

Related Recipes

  • Lockscreen

  • Save Indicator

  • Type Ahead

Additional Resources

  • distinctUntilChanged 📰 - Official docs

  • distinctUntilChanged - In Depth Dev Reference

  • Filtering operator: distinct and distinctUntilChanged 🎥 💵 - André Staltz


📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/distinctUntilChanged.ts