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

最后都变了- 提交于 2019-12-24 17:09:09

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/50677650/rxjs-how-to-wait-for-several-observables-even-if-one-or-many-fail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!