Home > Enterprise >  Retry observable queue three times (from the index where it failed)
Retry observable queue three times (from the index where it failed)

Time:10-14

I got an array of observables. I want to subscribe to each observable source provided only one at a time and not to subscribe to the next until the previous one is finished. If any fails I'd like to retry from the observable that failed (for a couple more times). I don't find a good, smart way to do that.

I'm sure there is more than one way, but I'm not even close to being 'fluent' in rxjs so I'm a bit lost rn. The project I'm working on is using rxjs 6.4.

Cheers and ty!

CodePudding user response:

You can use retry(X) inside concatMap() but it really depends on what behavior exactly you want:

source$
  .pipe(
    concatMap(val => makeRequest(val).pipe(
      retry(3), // Will retry only this request 3 times.
    )),
  );

With concat:

concat(...sources.map(obs => obs.pipe(retry(3))))
  .subscribe(result => {});

CodePudding user response:

You can use the RxJS operators SwitchMap and retry. The SwitchMaps chain the observables so that each one waits for the last to emit something.

obs1.pipe(
  retry(2)
  switchMap(res1 => obs2.pipe(retry(2)))
  switchMap(res2 => obs3.pipe(retry(2)))
).subscribe(res3 => console.log(res3))

EDIT:

What to do if you don't know the amount of observables:

let arr = [obs1$, obs2$, obs3$]

of(arr).pipe(
  ...(arr.reduce((p, q) => [...p, switchMap(e), retry(2)]))
).subscribe(console.log)
  • Related