💡 distinctUntilChanged uses ===
comparison by default, object references
must match!
💡 If you want to compare based on an object property, you can use
distinctUntilKeyChanged
instead!
( 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);
( 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);
( 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);
- distinctUntilChanged 📰 - Official docs
- Filtering operator: distinct and distinctUntilChanged 🎥 💵 - André Staltz
📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/distinctUntilChanged.ts