Home > OS >  RxJs fromEvent combined with retryWith
RxJs fromEvent combined with retryWith

Time:03-23

This is my code:

const searchBooks$: Observable<Book[]> = fromEvent(
      this.filter.nativeElement,
      'keyup'
    ).pipe(
      debounceTime(500),
      map((e: any) => {
        console.log('map');
        return e.target.value;
      }),
      distinctUntilChanged(),
      concatMap((search) => this.bs.getBooks(search)),
      shareReplay(),
      retryWhen((errors) => {
        console.log('error.. retrying n 2 seconds');
        return errors.pipe(delayWhen(() => timer(2000)));
      })
    );

when the endpoint fails in this.bs.getBooks(search) i receive the exception into retryWhen , but after 2 seconds no retry is performed.

What am I doing wrong?

CodePudding user response:

Instead of a concatMap, I would use a switchMap so that if the user enters a new character, the current call to the backend is "cancelled" (won't be observed if a result is returned) and a new one is made. I would also put the retryWhen purely on the call to the backend and not the entire stream:

const searchBooks$: Observable<Book[]> = fromEvent(
    this.filter.nativeElement,
    'keyup'
  ).pipe(
      debounceTime(500),
      map((e: any) => e.target.value),
      tap(data => console.log(data)),
      distinctUntilChanged(),
      switchMap((search) => 
         this.bs.getBooks(search)
            .pipe(retryWhen((errors) => errors.pipe(
               tap(error => console.log('error.. retrying n 2 seconds')),
               delayWhen(() => timer(2000))
            )))
      ),
      shareReplay(),
  );
  • Related