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

Bee*_*ice 4 rxjs angular 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();
  }  
}
Run Code Online (Sandbox Code Playgroud)

执行时ngOnInit,记录的内容如下:

一个发出

两个发射

两个收到

一个发出

三发射

三个收到

我不明白:为什么one发射两次?share管道中的操作符不应该创建twothree订阅相同的共享源吗?

来源 Stackblitz

mar*_*tin 5

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

因此,只要使用shareafter tap,它就会维护对其父级的一个订阅。

one = this.subject.pipe(tap(e => console.log('one emits')), share());
Run Code Online (Sandbox Code Playgroud)