且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

订阅者不应因可观察的错误而停止

更新时间:2022-04-14 02:46:00

这是正确的行为.您可以使用 catch() 运算符再次订阅同一个源 Observable(或在错误时订阅不同的).

That's correct behavior. You can use the catch() operator to subscribe to the same source Observable again (or a different one on error).

source
  .catch(err => Observable.of(null))
  .subscribe(...);

这只会在 next 处理程序中返回 null 而不是原始错误.

This will just return null in the next handler instead of the original error.

另请注意,如果订阅者没有任何 error 处理程序,则会重新抛出任何异常.

Also note that any exception is rethrown if the subscriber doesn't have any error handler.

例如,为了避免抛出您可能犯的错误:

For example to just avoid throwing an error you could make:

source
  ...
  .subscribe(..., error => {});

然而,这将始终取消订阅链,因为这是 Observables 的基本原则之一.它们发出零个或多个 next 通知和一个 completeerror 通知,但不会同时发出.

However this will always unsubscribe the chain because this is one of the basic principles of Observables. They emit zero or more next notifications and one complete or error notification but never both.

很难说你想解决什么问题你不想退订,有时你可以使用 Subject 并且只传递它 next 通知并忽略剩下的……:

It's hard to tell what problem are you trying to solve where you don't want to unsubscribe, sometimes you can use Subject and only pass it next notifications and ignore the rest...:

const subject = new Subject();
source.subscribe(val => subject.next(val));

subject.subscribe(...);