typescript - RXJS Subject - 阻止错误传播

标签 typescript rxjs rxjs5

当多个观察者订阅一个 RXJS Subject 时,是否可以阻止一个观察者传播错误并阻止其他观察者(稍后注册)看到该事件

Stackblitz 示例:https://stackblitz.com/edit/rxjs-cy7swm

const sub = new Subject<string>();

sub.asObservable().subscribe((val) => {
  console.log('1st sees: ' + val);
});

sub.asObservable().subscribe((val) => {
  console.log('2nd sees: ' + val);
  throw new Error('2nd throws error');
});

sub.asObservable().subscribe((val) => {
  console.log('3rd sees: ' + val);
});

sub.next('test');
sub.next('test2');

这里第三个观察者没有看到事件,因为第二个观察者抛出异常,并且 test2 值没有被任何东西看到,因为第一个错误有效地关闭了主题

1st sees: test
2nd sees: test
ERROR Error: 2nd throws error

没有明显包装每个订阅 block 在 try catch 中,是否有更好的 RXJS 框架方法来确保第三个观察者仍然看到值并且对 sub.next() 的第二次调用是也观察到了?

更新(根据 cartant 的回答):

这在 rxjs6 中得到了更好的处理 - 请参阅更新后的 Stackblitz 使用相同的代码,但没有副作用:https://stackblitz.com/edit/rxjs6-subject-err

最佳答案

这是 RxJS v5 的一个已知问题,它已在 v6 中得到解决 - 其中 synchronous error handling has been changed .

在 v6 中,您所看到的将不再发生。相反,从“监听器”中抛出的错误将被异步重新抛出,并且应用程序会将其视为未处理的错误。

有关详细信息,请参阅 this video .

关于typescript - RXJS Subject - 阻止错误传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52301297/

相关文章:

redux - 史诗不会对另一个史诗的 Action 使用react

Angular 服务 - 返回的对象类型是对象,而不是指定的泛型类型

angular - 如何在 Angular 2 中使用 rxjs 按间隔请求异步

typescript - 使用 typescript 将接口(interface)与 angular 2 中的 html 绑定(bind)

angular - 将 Rxjs 代码转换为 Angular 6 和最新的 rxjs

typescript - 如何在 TS 中输入装饰器

状态为 : 200 for URL: null 的 Angular 2 + NativeScript 响应

Angular 4.一系列http请求被取消

reactjs - 对 child 使用 “React.ReactNode”类型时出错。我应该使用哪种类型?

javascript - NestJS 无法解析 AuthServices 的依赖关系