distinctUntilChanged() not working as expected in angular 6

Viewed 5807

I have a method that returns an observable as follows

constructor(private _http: HttpClient) {}

getUsers(location){
   return this._http.get(`https://someurl?location=${location}`)
          .pipe(
              map((response: any) => response),
              distinctUntilChanged()
           )
}

(Please assume all the required dependencies are imported)

So in order to display the result of users, I call loadUsers method.

loadUsers(location){
   this.getUsers(location).subscribe( users => {
       this.userList = users;
    });
}

ngOnInit(){
    this.loadUsers('mumbai');
}

So the above code loads the list of users for me, for all the users who have location Mumbai.

Now I have a list of locations on the UI with the checkbox next to it like

Mumbai,
Delhi,
Kerala

So clicking on one location will call the loadUsers method with the location name as a parameter.

So when I click on Mumbai again from the checkbox ( before clicking on any other checkbox other than Mumbai) I do not want to loadUsers belonging to Mumbai again as it was already loaded on load.

I have read that distinctUntilChanged() can be used in such cases. However it doesn't seem to work for me as when I select Mumbai from the checkbox list, it still hits a call to loadUsers from Mumbai

PS - This is not the real use case. The above description is just an attempt to get my problem clear to you all.

I am a newbie into Angular and Rxjs. Please help.

1 Answers

your distinctUntilChanged is applied to the response this._http.get() returns. If you want to prevent invoking getUsers() again for the same location you would have to rewrite your code a bit to have your list of locations be observable // push a next location into a Subject so you can use distinctUntilChanged on this input list.

const currentLocation = new Subject();
on('click', () => currentLocation.next(this.value)); // on your location list items checkboxes

currentLocation.pipe(
  distinctUntilChanged(),
  mergeMap(location => loadUsers(location)
)
.subscribe(users => {
  this.userList = users;
});

I have left out a lot of boilerplate with regards to angular but i hope you get the gist of what the solution should be.

Related