【问题标题】:RxJS Observables: why does callback fire twice?RxJS Observables:为什么回调会触发两次?
【发布时间】:2018-08-16 12:10:08
【问题描述】:

考虑这个来自 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 会发出两次?管道中的share 运算符不应该使twothree 订阅相同的共享源吗?

Source on Stackblitz

【问题讨论】:

    标签: angular rxjs rxjs6


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-08
      • 1970-01-01
      • 2011-01-27
      • 2021-07-08
      • 2014-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多