'use distinctUntilChanged on objects
How can I have distinctUntilChanged work with objects like this
myObs = Observable.from([{foo: 'bar'}, {foo: 'bar'}]);
myObs.distinctUntilChanged()
.subscribe(value => {
// I only want to receive {foo: 'bar'} once
});
Solution 1:[1]
You need to pass a function inside the distinctUntilChanged that returns a boolean to make sure that the objects are the same.
Example
myObs. distinctUntilChanged((a, b) => a.foo === b.foo)
Solution 2:[2]
distinctUntilChanged takes a function comparator argument, since the default is to compare using === equality (which is always different for different object references):
// compare by .foo which is a primitive
myObs.distinctUntilChanged((x,y) => y.foo === x.foo)
.subscribe(value => {
// receive {foo: 'bar'} once
});
Solution 3:[3]
You can also use distinctUntilKeyChanged if you want to compare based on an object property.
myObs.distinctUntilKeyChanged('foo')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Fabio Carpinato |
| Solution 2 | Benjamin Gruenbaum |
| Solution 3 | Anh-Thi DINH |
