Observable.combineLatest continue even if one fails

有些话、适合烂在心里 提交于 2020-05-13 04:39:25

问题


I have a function that needs to resolve multiple documents from firebase

  fetchDocuments(documentIds: string[]): Observable<TreeNodeDocument[]> {
    const observables = [];
    for(let id of documentIds){
      observables.push(this.fetchDocument(id));
    }
    return Observable.combineLatest(observables, (...docs: TreeNodeDocument[]) => {
      //some transformations on the resolved documents
      return docs;
    });
  }

this.fetchDocument(id) returns an observable of type TreeNodeDocument.

This function works as long as all of the documents can be resolved. Now sometimes it happens that some of the documents cannot be resolved, then the respective fetchDocument(id) observable will fail. It is ok and expected that some of the documents cannot be resolved. However the Observable.combineLatest fails completely if one of them fails (I understand this is a good default behaviour).

My question is now, can I use combineLatest in a way so I get only the documents on which the fetch has worked and just ignore the ones on which it failed? Or can I achieve this in a different way?

Cheers


回答1:


You can pipe each source Observable (each this.fetchDocument(id)) with catchError that will replace the error notification with a dummy next item (or whatever you want).

for (let id of documentIds){
  observables.push(this.fetchDocument(id).pipe(
    catchError(() => of(null)),
  ));
}

...

Note, that you can't use just empty() or of() because both of them wouldn't emit any next item and combineLatest wouldn't work as you expect. Of course, instead of null you can use anything you want. The array of docs will have null at indices where a source Observable failed.



来源:https://stackoverflow.com/questions/52260559/observable-combinelatest-continue-even-if-one-fails

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