0
Follow
4
View

What is a forkJoin alternative that allows parallel requests to complete if one of them fails

daisyby 注册会员
2023-01-26 04:47

You can achieve that using forkJoin, however, you have to handle the errors for each sub Observable separately using catchError to prevent canceling the stream if any error occurred.

You can try something like the following:

// import { catchError } from 'rxjs/operators';
// import { forkJoin, of } from 'rxjs';

const posts = this.http
  .get('https://myApi.com/posts?userId=1')
  .pipe(catchError((err) => of(err)));
const albums = this.http
  .get('https://myApi.com/albums?userId=1')
  .pipe(catchError((err) => of(err)));

forkJoin([posts, albums]).subscribe((result) => {
  this.print(result[0], result[1]);
});
etdong 注册会员
2023-01-26 04:47

I would make a function like

forkJoinReplaceErrors(
  observables: Observable[],
  ifError: ObservableInput
) {
  return forkJoin(
    observables.pipe(
      catchError(() => ifError)
    )
  );
}

and then use that instead of forkJoin. Then it's more reusable and can be unit tested.