Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

distinctUntilChanged in nested pipe with switchMap

Tags:

rxjs5

rxjs6

I have an observable stream set up as below. I have an interval that is polling every two seconds. I then switchMap that to make two dependent API calls (mocked here with 'of's). After, I want to use distinctUntilChanged to make sure the final object is different. The only thing is that distinctUntilChanged doesn't fire.

I'm assuming it has SOMETHING to do with the fact that we are creating new streams and therefore never collects two objects to compare, but I don't fully understand.

interval(2000).pipe(
    switchMap(() => loadData()),
  )
  .subscribe(res => console.log(res)); // { name: 'test' } is printed every two seconds

function loadData() {
  return of('API call').pipe(
     mergeMap(numb => of({ name: 'test' })),
     distinctUntilChanged((prev, cur) => {
       console.log('CompareFn'); // This will never fire.
       return JSON.stringify(prev) === JSON.stringify(cur)})
  );
}

Stackblitz: https://stackblitz.com/edit/rxjs-ko6k3c?devtoolsheight=60

In this case, I would like there to only be a single value ever printed from the next handler as distinctUntilChanged should stop all values after the first.

Would appreciate an explanation as to why this isn't working as I would expect it to.

like image 574
CuriousGeorge Avatar asked Sep 07 '25 06:09

CuriousGeorge


1 Answers

the problem is that your distinctUntilChanged is operating on the inner observable, not the outter... you need to do this

interval(2000).pipe(
    switchMap(_ => loadData()),
    distinctUntilChanged((prev, cur) => {
       console.log('CompareFn');
       return JSON.stringify(prev) === JSON.stringify(cur);
    })
  )
  .subscribe(res => console.log(res));

function loadData() {
  return of('API call').pipe(
     mergeMap(numb => of({ name: 'test' }))
  );
}

in your prior set up, only one value ever reached distinctUntilChanged as the interval switched into a new observable via switch map.

like image 138
bryan60 Avatar answered Sep 11 '25 00:09

bryan60