Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS Observables: why does callback fire twice?

Consider this code, from an Angular 6 component:

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();
  }  
}

When ngOnInit executes, this is what gets logged:

one emits

two emits

two received

one emits

three emits

three received

I don't understand: why does one emit twice? Shouldn't the share operator in its pipe make two and three subscribe to the same shared source?

Source on Stackblitz

like image 602
BeetleJuice Avatar asked Oct 18 '25 05:10

BeetleJuice


1 Answers

The share() operator multicasts at the point you use it. So when you use it before tap then tap still has two observers.

So just use share after tap and it'll maintain one subscription to its parent.

one = this.subject.pipe(tap(e => console.log('one emits')), share());
like image 179
martin Avatar answered Oct 20 '25 20:10

martin