Retry 5 times after ever 3 seconds once the document.hasFocus() return true

711 Views Asked by At

Angular 11: I have a requirement where my mobile website will take users to another apps' popup. Once the user comes back to my mobile website I have to make an HTTP GET call. If response.await===true or an error then after 3 seconds I have to try again and repeat this process, the max attempt is 5. And if the overall process (ie when users come back to my mobile website) is >20sec I have to abort the operation and throw an error.

initiateProcess(){
        let index = 1;
        let tries=4;
        return of(1).pipe(
            switchMap(()=>this.httpService.getFromApi(SOME_API)),
            retryWhen(error=>error.pipe(delay(3000),take(tries),mergeMap(error => {
                if (++index > tries) {
                  return throwError('time out');
                }
                return of(error);
            }))),
        );
    }

This is what I have done so far. But I am stuck.

1

There are 1 best solutions below

6
Mrk Sef On

You can turn your other fail condition into an error, the rest should just follow?

interface ResponseType {
  await: boolean
}

initiateProcess(): Observable<ResponseType> {
  let tries=4;

  const timeout$ = timer(20 * 1000).pipe(
    tap(_ => {throw "Error: 20 Seconds have passed without Api response";})
  );

  const api$ = defer(
    () => this.httpService.getFromApi(SOME_API)
  ).pipe(
    tap((res: ResponseType) => {
      if (res.await) throw "Error: Api response.await === true";
    }),
    retryWhen(error$ => error$.pipe(
      take(tries),
      delay(3000)
    ))
  );

  return merge(api$, timeout$);
}