unkreativ
unkreativ

Reputation: 480

RxJS: How to wait for several observables, even if one or many fail

I was using the zip operator to wait for three observables and process the result simultaneously:

Observable
   .zip(
      this.sapService.getProductSpareParts(this.identForm.get('ident').value),
      this.mediacacheService.getMediaItemsByIdent(this.identForm.get('ident').value),
      this.mediacacheService.getMetaInfos(this.identForm.get('ident').value)
    )
    .subscribe((results: any) => {
      // do stuff
    });

It is possible that one or many of those three observables fail and return a 500 result. In this case, all other pending observables will be cancled.

How can I ignore the erroneous observables, don't cancel them and wait for the remaining observables to complete, to process the results of the successfull observables?

Upvotes: 1

Views: 1261

Answers (2)

Julien Ambos
Julien Ambos

Reputation: 2088

As Robin suggested, use the catchError operator with the pipe operator on each of the observables:

Observable
  .zip(
    this.sapService.getProductSpareParts(this.identForm.get('ident').value).pipe(catchError(val => of(`I caught: ${val}`))),
    ...
  )
  .subscribe((results: any) => {
    // do stuff
  });

See https://www.learnrxjs.io/operators/error_handling/catch.html for more information.

Upvotes: 2

Ankur Shah
Ankur Shah

Reputation: 430

Have a look a below solution i think this will solve your problem

var source = Rx.Observable.onErrorResumeNext(
     Rx.Observable.just(42),
     Rx.Observable.throw(new Error()),
     Rx.Observable.just(56),
     Rx.Observable.throw(new Error()),
     Rx.Observable.just(78)
   );

var subscription = source.subscribe(
     data => console.log(data)
   ); 

Result

// => 42

// => 56

// => 78

Upvotes: 2

Related Questions