订阅者不应因可观察的错误而停止 [英] Subscriber should not stop on error in observable

查看:35
本文介绍了订阅者不应因可观察的错误而停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个订阅者,它在出错时自动取消订阅:

I am struggling with a subscriber, which automatically unsubscribe itself on error:

observable
  .subscribe(
    (data) => {
      // some logic encountering an error during execution
      // comparable to throw new Error()
    }
  )

我可以使用 try/catch 来防止它:

I can prevent it with using try / catch:

observable
  .subscribe(
    (data) => try { 
        // some logic encountering an error during execution
        // comparable to throw new Error()
      } catch(e) {
      }
  )

但这感觉像是一种解决方法.

But it feels like a work around.

我已经深入研究了 Subscriber 和 SafeSubscriber 的来源,它们会在出错时自动调用取消订阅:

I have dived into the source of Subscriber and SafeSubscriber, which automatically call unsubscribe on error:

  private __tryOrUnsub(fn: Function, value?: any): void {
    try {
      fn.call(this._context, value);
    } catch (err) {
      this.unsubscribe();
      throw err;
    }
  }

实现自己的订阅者或使用 try/catch 是阻止这种行为的唯一方法吗?

Is the only way to prevent this behavior to implement an own Subscriber or using try / catch?

推荐答案

这是正确的行为.您可以使用 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(...);

这篇关于订阅者不应因可观察的错误而停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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