Mateusz Gebroski
Mateusz Gebroski

Reputation: 1334

RxJs Return old value when when filter return false

The main purpose of this code is to check if values exist in store and prevent additional request to server. Whole logic works fine but unfortunately when filter returns false selector is not applied to observable and array is empty even if values are in store.

  this.events$ = this.paginationService.page$.pipe(
      switchMap(pageIndex => this.store.pipe(
        delay(0),

        //get objects from store
        select(selectEventsPageByGenre(this.musicGenre, { pageIndex: pageIndex, pageSize: 3 })),

        //if there are no objects from select() the dispatch server request
        filter(events => events.length === 0),
        map(() => {
          this.store.dispatch(new EventsPageRequested({
            musicGenre: MusicGenre[this.musicGenre.toUpperCase()],
            page: {
              pageIndex: pageIndex,
              pageSize: 6
            }
          }));

          return [];
        })
      ))
    );

How to return values from selector when filter returns false (if array is not empty)?

Thanks in advance

Upvotes: 0

Views: 662

Answers (1)

JB Nizet
JB Nizet

Reputation: 692053

Simply remove the filter(), and replace the map() by

    map(() => {
      if (events.length > 0) {
        return events;
      }
      this.store.dispatch(new EventsPageRequested({
        musicGenre: MusicGenre[this.musicGenre.toUpperCase()],
        page: {
          pageIndex: pageIndex,
          pageSize: 6
        }
      }));

      return [];
    })

Upvotes: 1

Related Questions