BeetleJuice
BeetleJuice

Reputation: 40886

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

Upvotes: 4

Views: 1710

Answers (1)

martin
martin

Reputation: 96891

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

Upvotes: 5

Related Questions