Home > Back-end >  distinctUntilChanged() does not get executed on page load
distinctUntilChanged() does not get executed on page load

Time:03-01

When a page is loaded I run the following method and use the returned list in dropdown.

The tap and the switchMap block gets executed but not what's in distinctUntilChanged on page load.

After the page load, distinctUntilChanged gets executed correctly if I change the value of "formControl"

Why isn't distinctUntilChanged() executing on page load?

        const sourceA$ = formControl.valueChanges.pipe(startWith('user-input-value'));
        return combineLatest(([sourceA$, sourceB$, sourceC$])).pipe(
                tap(([a, b, c]) => {
                  console.log(a); // gets executed on page load
                }),
                distinctUntilChanged(([a, b, c], [a2, b2, c2]) => {
                  return a === a2; // does not get executed on page load
                }),
                switchMap(([a, b, c]) => {
                  console.log(a); // gets executed on page load
                  return of([]);
                })
            );

CodePudding user response:

distinctUntilChanged expect 2 values: the current and the previous. It compare both and run only if the latter is different from the previous.

In your case you not have a previous value, because on page load you cannot have any previous value, so your operator never works.

For more info: distinctUntilChange

CodePudding user response:

Based on the implementation of the distinctUntilChanged operator in [email protected], it checks if it's the first value, then it always emits it without calling the provided/predefined comparator function.

From the distinctUntilChanged implementation:

If it's the first value, we always emit it. Otherwise, we compare this key to the previous key, and if the comparer returns false, we emit.

if (first || !comparator!(previousKey, currentKey)) { // ... }

So, in your case, the comparator function you provided won't be called at the first time until the next value comes.

  • Related