use distinctUntilChanged on objects

Viewed 4333

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
});
3 Answers

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)

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
});

You can also use distinctUntilKeyChanged if you want to compare based on an object property.

myObs.distinctUntilKeyChanged('foo')
Related