angular - RxJS 可观察对象 : why does callback fire twice?

标签 angular rxjs rxjs6

考虑这段来自 Angular 6 组件的代码:

class AppComponent  {
  subject = new Subject<any>();
  one = this.subject.pipe(share(), tap(e => log('one emits')));
  two = this.one.pipe(tap(e => log('two emits')));
  three = this.one.pipe(delay(500), tap(e => log('three emits')));

  ngOnInit() {
    this.two.subscribe(e => log('two received'));
    this.three.subscribe(e => log('three received'));    
    this.subject.next();
  }  
}

ngOnInit 执行时,这是记录的内容:

one emits

two emits

two received

one emits

three emits

three received

我不明白:为什么 one 发出两次?管道中的 share 运算符不应该让 twothree 订阅相同的共享源吗?

Source on Stackblitz

最佳答案

share() 运算符在您使用它时进行多播。所以当你在 tap 之前使用它时,tap 仍然有两个观察者。

所以只需在 tap 之后使用 share ,它就会维护一个对其父级的订阅。

one = this.subject.pipe(tap(e => console.log('one emits')), share());

关于angular - RxJS 可观察对象 : why does callback fire twice?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51876752/

相关文章:

javascript - 更改嵌入推文的最大宽度

javascript - 在 Angular 2 中加载 jQuery 函数

angular - 尝试使用 Firebase admin SDK 时出错

angular - 是否建议订阅管道内的商店(ngRx)?

angular - 我如何使用 catchError() 并仍然返回带有 rxJs 6.0 的类型化 Observable?

angular - "async"管道不呈现流更新

rxjs - 如何同步 RxJS 更新,以便中间值不会通过流传递?

node.js - rxjs 订阅返回重复项

javascript - 为什么可观察管道在组件中不起作用?

javascript - 使用 rxjs 或 native javascript 从 json 中提取特定键