51

I have a stream of objects and I need to compare if the current object is not the same as the previous and in this case emit a new value. I found distinctUntilChanged operator should do exactly what I want, but for some reason, it never emits value except the first one. If I remove distinctUntilChanged values are emitted normally.

My code:

export class SettingsPage {
    static get parameters() {
        return [[NavController], [UserProvider]];
    }

    constructor(nav, user) {
        this.nav = nav;
        this._user = user;

        this.typeChangeStream = new Subject();
        this.notifications = {};
    }

    ngOnInit() {

        this.typeChangeStream
            .map(x => {console.log('value on way to distinct', x); return x;})
            .distinctUntilChanged(x => JSON.stringify(x))
            .subscribe(settings => {
                console.log('typeChangeStream', settings);
                this._user.setNotificationSettings(settings);
            });
    }

    toggleType() {
        this.typeChangeStream.next({
            "sound": true,
            "vibrate": false,
            "badge": false,
            "types": {
                "newDeals": true,
                "nearDeals": true,
                "tematicDeals": false,
                "infoWarnings": false,
                "expireDeals": true
            }
        });
    }

    emitDifferent() {
        this.typeChangeStream.next({
            "sound": false,
            "vibrate": false,
            "badge": false,
            "types": {
                "newDeals": false,
                "nearDeals": false,
                "tematicDeals": false,
                "infoWarnings": false,
                "expireDeals": false
            }
        });
    }
}
5
  • Is typeChangeStream an Observable? Hard to tell what's wrong without seeing what code is creating that / etc. May 11, 2016 at 20:34
  • Please have a look at stackoverflow.com/help/mcve for guidelines to deal with 'it does not work' questions. Basically post a minimally verifiable example that reproduces the error, and post the expected behaviour and how it is different from the current behavior. Talk about JSON stringifying you need to know that it is not a bullet proof method for checking equality of objects. {"a" : 2, "b":1} is for example different from {"b":1, "a":2} while these are the same objects May 11, 2016 at 23:02
  • Sorry for that, i added more code. I don't need bullet proof object equality check, i am sure in this case object will be everytime i same order. May 12, 2016 at 5:25
  • did u solve this problem? i have the same with BehaviorSubject, and it emits prev and curr same result, wtf..
    – Den Kerny
    Mar 6, 2020 at 8:21
  • @DanielSuchý it would be good IMO to accept the answer that did work for you Jan 29, 2021 at 11:17

11 Answers 11

67

I had the same problem, and fixed it with using JSON.stringify to compare the objects:

.distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b))

This code will work if the attriutes are in the same order, if not it may break, so here's a quick fix for that (be careful this method is slower)

.distinctUntilChanged((a, b) => JSON.stringify(a).split('').sort().join('') === JSON.stringify(b).split('').sort().join(''))

12
  • I am filling in my input my unit cost for a product, with the same logic, but now I can only type 1 number at a time , unless i go back and click on the field. I would like to be able to type in multiple digits at a time which is the normal default. How can I do this Sep 12, 2018 at 21:35
  • 1
    Have you tried the throttling or debouncing rxJS operators ? Sep 13, 2018 at 10:03
  • 1
    this will give you incorrect true when you delete a property and add it back.
    – Milad
    Nov 15, 2018 at 5:00
  • 3
    I didn't understand your scenario, JSON.stringify will simply convert the object to string. Even if you don't have the same properties order it won't work ! Nov 20, 2018 at 13:14
  • 1
    JSON.stringify({a:1, b:2}) === JSON.stringify({b:2, a:1}) this is false, while the result should have been ture
    – Reza
    Sep 7, 2020 at 0:48
34

When you have lodash in your application anyway, you can simply utilize lodash's isEqual() function, which does a deep comparison and perfectly matches the signature of distinctUntilChanged():

.distinctUntilChanged(isEqual),

Or if you have _ available (which is not recommended anymore these days):

.distinctUntilChanged(_.isEqual),
2
  • Can you clarify what you mean in the sentence: "Or if you have _ available (which is not recommended anymore these days):" because you literally just said if you have lodash in your application you can utilize lodash's isEqual() function, but isn't using "_" the way to use lodash to call the isEqual method??
    – Bobby_Cheh
    Mar 25, 2022 at 17:27
  • 4
    @Bobby_Cheh When you import the _-Symbol, this includes all of lodash's functionality, whether you use it or not. This cannot be reduced to the really needed ones later to reduce the resulting bundle size in a build process (this is called "Tree Shaking", because all unconnected things fall of :-) ). When you just require the single functions you need, it's only theses that get bound to your final program bundle: e.g. import {isEqual} from 'lodash'. Now it's tree-shakeable, so all the functions of lodash you didn't use (probably most part of lodash ;-) ) will not be included.
    – hoeni
    Mar 27, 2022 at 10:49
25

I finally figure out where problem is. Problem was in version of RxJS, in V4 and earlier is different parameters order than V5.

RxJS 4:

distinctUntilChanged = function (keyFn, comparer)

RxJS 5:

distinctUntilChanged = function (comparer, keyFn)

In every docs today, you can find V4 parameters order, beware of that!

2
  • How did you fix this? What did you change? If you can tell this it would be great. Aug 16, 2018 at 13:35
  • 1
    @Harsimer swap comparer and key function Sep 24, 2019 at 19:56
14

You can also wrap the original distinctUntilChanged function.

function distinctUntilChangedObj<T>() {
  return distinctUntilChanged<T>((a, b) => JSON.stringify(a) === JSON.stringify(b));
}

This lets you use it just like the original.

$myObservable.pipe(
  distinctUntilChangedObj()
)

Cavets

This method also has several pitfalls as some commenters have pointed out.

  1. This will fail if the objects fields are ordered differently;
JSON.stringify({a:1, b:2}) === JSON.stringify({b:2, a:1})
// will return false :(
  1. This JSON.stringify will also throw an error if the object has circular references. For example stringify'ing something from the firebase sdk will lead you to these errors:
TypeError: Converting circular structure to JSON

Robust Solution

Use the deep-object-diff library instead of JSON.stringify. This will solve the above problems 👍

import { detailedDiff } from 'deep-object-diff';

function isSame(a, b) {
  const result = detailedDiff(a, b); 
  const areSame = Object.values(result)
    .every((obj) => Object.keys(obj).length === 0);
  return areSame;
}

function distinctUntilChangedObj<T>() {
  return distinctUntilChanged<T>((a, b) => isSame(a, b));
}
7
  • even though it works, it messes with the pipeline objects
    – Frik
    Aug 17, 2020 at 16:11
  • @Frik how so? JSON.stringify() shouldn't mess/mutate anything right? If you have circular json in your objects, then you might need to use another package which can stringify it properly npmjs.com/package/circular-json Aug 18, 2020 at 0:53
  • 1
    If you're using typescript, then you could also do function distinctUntilChangedObj<T>() { return distinctUntilChanged<T>((a, b) => JSON.stringify(a) === JSON.stringify(b)); }. This will preserve the type correctly, but only if you're using typescript Aug 19, 2020 at 7:54
  • 1
    Nice answer! This will be very useful.
    – pjdicke
    Dec 18, 2020 at 19:16
  • 1
    That's true @TamusJRoyce, there's other ways it can fail too, for example circular references in the objects. I've updated answer to address these problems Mar 12, 2022 at 9:00
11

From RxJS v6+ there is distinctUntilKeyChanged

https://www.learnrxjs.io/operators/filtering/distinctuntilkeychanged.html

const source$ = from([
  { name: 'Brian' },
  { name: 'Joe' },
  { name: 'Joe' },
  { name: 'Sue' }
]);

source$
  // custom compare based on name property
  .pipe(distinctUntilKeyChanged('name'))
  // output: { name: 'Brian }, { name: 'Joe' }, { name: 'Sue' }
  .subscribe(console.log);
1
  • 1
    FYI, if name was an object like {name: {first: 'Brian'}} this doesn't work as it doesn't compare the the entire objects.
    – pjdicke
    Dec 18, 2020 at 19:19
4

Mehdi's solution although fast but wouldn't work if the order is not maintained. Using one of deep-equal or fast-deep-equal libraries:

.distinctUntilChanged((a, b) => deepEqual(a, b))
1
  • there is structuredClone polyfil/new standard. Why isn't there structuredEquals replacement for lodash? lodash isn't compiler friendly when it comes to tree shaking Mar 10, 2022 at 20:27
3

The answers suggesting a deep compare all fail if the observable is actually emitting a modified version of the same object, as the "last" value that is passed to the comparison will be the same as the current, every time.

We've hit this using a BehaviorSubject where it just so happens that the same object is passed to .next() each time.

In this case, there is no solution using the default distinctUntilChanged, no matter what comparison function you use.

0
0

If you change the value mutably, none of the other answers work. If you need to work with mutable data structures, you can use distinctUntilChangedImmutable, which deep copies the previous value and if no comparison function is passed in, will assert that the previous and the current values deep equals each other (not === assertion).

1
  • Class constructor Subscriber cannot be invoked without 'new' at new DistinctUntilChangedSubscriber
    – Den Kerny
    Mar 6, 2020 at 8:03
0

You can also make your own filter:

function compareObjects(a: any, b: any): boolean {
  return JSON.stringify(a) === JSON.stringify(b);
}

export function distinctUntilChangedObject() {
  return function<T>(source: Observable<T>): Observable<T> {
    return new Observable(subscriber => {
      let prev: any;
      let first = true;
      source.subscribe({
        next(value) {
          if (first) {
            prev = value;
            subscriber.next(value);
            first = false;
          } else if (!compareObjects(prev, value)) {
            prev = value;
            subscriber.next(value);
          }
        },
        error(error) {
          subscriber.error(error);
        },
        complete() {
          subscriber.complete();
        }
      });
    });
  };
}
0

For those considering JsonStringify to be slow or unreliable (because of different property order) the example below might help for an object array. Its primary key is a property called 'id'.

same(prev: BasketItem[], next: BasketItem[]): boolean {
    if (prev?.length != next?.length)
        return false;

    // verify that all of the ids are contained in both arrays
    for (var i = 0; i < prev.length; i++) {
        if (!prev.some(x => x.id == next[i].id))
            return false;
        if (!next.some(x => x.id == prev[i].id))
            return false;
    }
    return true;
}

I call it a as follows

.pipe(distinctUntilChanged((prev, curr) => this.same(prev, curr)))

example for the object array :

[ {id:'d7273481-e99b-4d72-84eb-826fbf52e4e9' , price:'44.02'}

, {id:'11f125e3-c190-4177-a656-7b107a7d687c' , price:'54.88'} ]

0

I had to do this:

import { cloneDeep, isEqual } from 'lodash-es'

observable$.pipe(
  ... other stuff
  map(x => cloneDeep(x)),
  distinctUntilChanged(isEqual)
  ... other stuff
)

if x is getting mutated, cloneDeep seems to be necessary to make distinctUntilChanged work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.