RxJS Observables:为什么回调会触发两次?
RxJS Observables: why does callback fire twice?
考虑这段代码,来自 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
运算符不应该使 two
和 three
订阅相同的共享源吗?
share()
运算符在您使用它时进行多播。所以当你在 tap
之前使用它时 tap
仍然有两个观察者。
所以只需在 tap
之后使用 share
,它就会保持对其父级的订阅。
one = this.subject.pipe(tap(e => console.log('one emits')), share());
考虑这段代码,来自 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
运算符不应该使 two
和 three
订阅相同的共享源吗?
share()
运算符在您使用它时进行多播。所以当你在 tap
之前使用它时 tap
仍然有两个观察者。
所以只需在 tap
之后使用 share
,它就会保持对其父级的订阅。
one = this.subject.pipe(tap(e => console.log('one emits')), share());