代码之家  ›  专栏  ›  技术社区  ›  BeetleJuice

RxJS观察:为什么回调会触发两次?

  •  3
  • BeetleJuice  · 技术社区  · 7 年前

    从一个角度为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 管道制造商中的操作员 two three

    Source on Stackblitz

    1 回复  |  直到 7 年前
        1
  •  4
  •   martin    7 年前

    这个 share() 操作员在您使用它时进行多播。所以你以前用它的时候 tap 然后 仍有两名观察员。

    所以就用 share 之后 它将维护对其父级的一个订阅。

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