即使一个失败,Observable.combineLatest仍会继续 [英] Observable.combineLatest continue even if one fails

查看:66
本文介绍了即使一个失败,Observable.combineLatest仍会继续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要从Firebase解析多个文档的功能

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)返回类型为 TreeNodeDocument 的可观察对象.

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

只要可以解决所有文档,此功能就起作用.现在有时会发生某些文档无法解析的情况,因此相应的 fetchDocument(id)可观察项将失败.可以并希望某些文档无法解决.但是,如果其中一个失败,则 Observable.combineLatest 会完全失败(我知道这是一种很好的默认行为).

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).

我的问题是,现在是否可以以某种方式使用 combineLatest ,这样我就只能获取在其上可进行提取的文档,而忽略那些在其上不能读取的文档?还是可以通过其他方式实现这一目标?

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?

欢呼

推荐答案

您可以使用 catchError 用管道传输每个可观察的源(每个 this.fetchDocument(id))将 error 通知替换为虚拟的 next 项目(或所需的任何内容).

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)),
  ));
}

...

请注意,您不能仅使用 empty() of(),因为它们都不发出任何 next item和 combineLatest 无法正常工作.当然,除了 null ,您还可以使用任何您想要的东西.文档数组将在源Observable失败的索引处具有 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.

这篇关于即使一个失败,Observable.combineLatest仍会继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆