0

我有几个 observable 与 combineLatest组合在一个 observable 中。此外,我还有一个内部switchMap可观察对象,在实际示例中向远程服务器发出 http 请求。

现在我想知道,如果switchMap返回错误,组合的可观察对象如何继续工作?

我在这里创建了简化的示例

//emit every 2.5 seconds
const first = interval(2500);
//emit every 2 seconds
const second = interval(2000);
//emit every 1.5 seconds
const third = interval(1500);
//emit every 1 second
const fourth = interval(1000);

let count = 0;

//emit outputs from one observable
const example = combineLatest(
  first.pipe(mapTo("FIRST!")),
  second.pipe(mapTo("SECOND!")),
  third.pipe(mapTo("THIRD")),
  fourth.pipe(mapTo("FOURTH"))
)
  .pipe(
    switchMap(data => {
      console.log(data);
      count++;
      // here lets asume in some cases http request getting error
      return count < 5 ? of("switchMap") : throwError("This is an error!");
    }),
    catchError(err => of(err))
  )
  .subscribe(val => console.log(val));

输出

["FIRST!", "SECOND!", "THIRD", "FOURTH"]
switchMap
["FIRST!", "SECOND!", "THIRD", "FOURTH"]
switchMap
["FIRST!", "SECOND!", "THIRD", "FOURTH"]
switchMap
["FIRST!", "SECOND!", "THIRD", "FOURTH"]
switchMap
["FIRST!", "SECOND!", "THIRD", "FOURTH"]
This is an error!

所以在得到error combineLatestobservable的工作停止之后。在我的真实示例中,我有 4 个过滤器,在更改过滤器后,我发出 http 请求。

4

1 回答 1

1

combineLatest发生错误时,流本身将结束。
您可以通过将 . 添加catchError到您的switchMap.

这样,主流就不会改变,并且会继续存在。

const first  = interval(2500);
const second = interval(2000);
const third  = interval(1500);
const fourth = interval(1000);

let count = 0;

combineLatest(
  first.pipe(mapTo("FIRST!")),
  second.pipe(mapTo("SECOND!")),
  third.pipe(mapTo("THIRD")),
  fourth.pipe(mapTo("FOURTH"))
).pipe(
  switchMap(data => {
    count++;
    const obs$ = count < 5
      ? of("switchMap")
      : throwError("This is an error!");

    return obs$.pipe(
      catchError(err => of(err))
    );
  })
).subscribe(val => console.log(val));
于 2021-02-10T13:19:36.830 回答