Assigning empty array and distinctUntilChanged issue

Viewed 11

I have next rxjs code that checked if query length is > 1 then the rest operators execute:

 o$.pipe(
    filter((query) => query.length > 1),
    distinctUntilChanged(),
    switchMap((query) => {
      return this.data.query(query);
    })
  )
  .subscribe((data) => {
    this.localData = data; //returns array
  });

I want to assign this.localData = [] in case if query.length === 0. So thought to use operator like tap() above filter() where I would put that logic, but distinctUntilChanged() braking the logic because in case if cur value is equal to prev value the localData will be lost:

  o$.pipe(
    filter((query) => query.length > 1),
    tap((query) => {
      if(query.length === 1) {
        this.localData = [];
      }
    }),
    distinctUntilChanged(),
    switchMap((query) => {
      return this.data.query(query);
    })
  )
  .subscribe((data) => {
    this.localData = data; //returns array
  });

Any ideas how to fix?

1 Answers

Why even use the filtering step if you still want to pass data to the subscriber of the observable? I suggest to just perform the logic in the switchMap operator. In case of query.length > 1 the querying for data will be performed. In all other cases an empty array is passed to the subscriber:

  o$.pipe(
    distinctUntilChanged(),
    switchMap((query) => {
      return query.length > 1 ? data.query(query) : of([]);
    })
  )
  .subscribe((data) => {
    this.localData = data; //returns array
  });
Related