Learn RxJS
Search…
distinctUntilChanged

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!
​​
​
​

Examples

Example 1: distinctUntilChanged with basic values
1
// RxJS v6+
2
import { from } from 'rxjs';
3
import { distinctUntilChanged } from 'rxjs/operators';
4
​
5
// only output distinct values, based on the last emitted value
6
const source$ = from([1, 1, 2, 2, 3, 3]);
7
​
8
source$
9
.pipe(distinctUntilChanged())
10
// output: 1,2,3
11
.subscribe(console.log);
Copied!
Example 2: distinctUntilChanged with objects
1
// RxJS v6+
2
import { from } from 'rxjs';
3
import { distinctUntilChanged } from 'rxjs/operators';
4
​
5
const sampleObject = { name: 'Test' };
6
​
7
//Objects must be same reference
8
const source$ = from([sampleObject, sampleObject, sampleObject]);
9
​
10
// only emit distinct objects, based on last emitted value
11
source$
12
.pipe(distinctUntilChanged())
13
// output: {name: 'Test'}
14
.subscribe(console.log);
Copied!
Example 3: Using custom comparer function
1
// RxJS v6+
2
import { from } from 'rxjs';
3
import { distinctUntilChanged } from 'rxjs/operators';
4
​
5
// only output distinct values, based on the last emitted value
6
const source$ = from([
7
{ name: 'Brian' },
8
{ name: 'Joe' },
9
{ name: 'Joe' },
10
{ name: 'Sue' }
11
]);
12
​
13
source$
14
// custom compare for name
15
.pipe(distinctUntilChanged((prev, curr) => prev.name === curr.name))
16
// output: { name: 'Brian }, { name: 'Joe' }, { name: 'Sue' }
17
.subscribe(console.log);
Copied!

Additional Resources