Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RxJs fromEvent combined with retryWith

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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(),
  );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading