Solinas3000
Solinas3000

Reputation: 21

distinctUntilChanged() on BehaviourSubject don't work

My package.json:

searchTextValueSubject is a BehaviorSubject

import { debounceTime } from 'rxjs/operators';
import { distinctUntilChanged } from 'rxjs/operators';
import { pipe } from 'rxjs';

this.sharingVariableService
    .searchTextValueSubject
    .pipe(
        distinctUntilChanged((x, y) => {
            console.log(y.BarCodeS === x.BarCodeS);
            console.log(y.BarCodeS);
            console.log(x.BarCodeS);
            return y.BarCodeS === x.BarCodeS
        })
    )
    .subscribe((searchTextValue) => {
        this.searchTextValue = searchTextValue;
        this.getRessourceHardware(this.serverDataRessourceHardware._meta.max_results, this.searchTextValue);
    });

Result :

true, 'd', 'd'

true, 'da', 'da'

Expected :

False, ' ', 'd'

False, 'd', 'da'

I probably don't understand something. Could you please point me to the right direction ?

Upvotes: 1

Views: 5270

Answers (1)

Miller
Miller

Reputation: 2822

It looks like you might be sending mutated values to searchTextValueSubject.

Make sure your code is not doing something like this...

let value = {BarCodeS: 'd'}
this.sharingVariableService.searchTextValueSubject.next(value);

value.BarCodeS = 'da'; // wrong!
this.sharingVariableService.searchTextValueSubject.next(value);

The right way is this:

const value0 = {BarCodeS: 'd'}
this.sharingVariableService.searchTextValueSubject.next(value0);

const value1 = {...value0, BarCodeS: 'da'}; // right
this.sharingVariableService.searchTextValueSubject.next(value1);

Also note that the distinctUntilChanged comparer function is never called on the first emission (the first emission is necessarily distinct)

Upvotes: 2

Related Questions