distinctUntilChanged

signature: distinctUntilChanged(compare: function): Observable

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


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


Examples

Example 1: distinctUntilChanged with basic values

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { distinctUntilChanged } from 'rxjs/operators';
  3. //only output distinct values, based on the last emitted value
  4. const myArrayWithDuplicatesInARow = from([1, 1, 2, 2, 3, 1, 2, 3]);
  5. const distinctSub = myArrayWithDuplicatesInARow
  6. .pipe(distinctUntilChanged())
  7. //output: 1,2,3,1,2,3
  8. .subscribe(val => console.log('DISTINCT SUB:', val));
  9. const nonDistinctSub = myArrayWithDuplicatesInARow
  10. //output: 1,1,2,2,3,1,2,3
  11. .subscribe(val => console.log('NON DISTINCT SUB:', val));
Example 2: distinctUntilChanged with objects

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { distinctUntilChanged } from 'rxjs/operators';
  3. const sampleObject = { name: 'Test' };
  4. //Objects must be same reference
  5. const myArrayWithDuplicateObjects = from([
  6. sampleObject,
  7. sampleObject,
  8. sampleObject
  9. ]);
  10. //only out distinct objects, based on last emitted value
  11. const nonDistinctObjects = myArrayWithDuplicateObjects
  12. .pipe(distinctUntilChanged())
  13. //output: 'DISTINCT OBJECTS: {name: 'Test'}
  14. .subscribe(val => console.log('DISTINCT OBJECTS:', val));

Additional Resources


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