Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 and RxJS 5 Observable.share()

Running Angular 2 RC4 with RxJS 5 beta 6, I'm having a hard time figuring out why my observable is not shared across subscribers. I tried to follow instructions carefully to no avail. My component is below, but you can see it run live at this Plunker

template

<div> Toggle sub 1:
   <button (click)="subOne=!subOne">{{subOne?'One is ON ':'One is OFF'}}</button>
</div>
<div> Toggle sub 2:
   <button (click)="subTwo=!subTwo">{{subTwo?'Two is ON ':'Two is OFF'}}</button>
</div>
<ul><li *ngFor="let L of log.slice(-16)">{{L}}</li></ul>

class

_subOne = false;
get subOne(){return this._subOne};
set subOne(val){
    this._subOne = val;
    //if set to true, subscribe
    if(val) this.subscriptions.one =
        this.source().subscribe(d=>this.print('One sees '+d));

    //else, unsubscribe
    else this.subscriptions.one.unsubscribe();
}

_subTwo = false;
get subTwo(){return this._subTwo};
set subTwo(val){
    this._subTwo = val;
    if(val) this.subscriptions.two =
        this.source().subscribe(d=>this.print('Two sees '+d));
    else this.subscriptions.two.unsubscribe();
}

subscriptions = {'one':null,'two':null};
source(){
    return Observable.interval(3000)
        .do(()=>this.print("*******EMITTING*******")).share();
}

print(value){this.log.push(value);}
log=[];

Output

enter image description here

I expected the subscribers to share the same observable since I use the .share() operator. Why are they not?

like image 547
BeetleJuice Avatar asked Sep 09 '26 21:09

BeetleJuice


1 Answers

I think that it's because you create an observable each time you call the source method. You need to subscribe on the same observable instance.

source:Observable = this.source(); // <-----

set subOne(val){
  this._subOne = val;
  if(val) this.subscriptions.one =
    this.source.subscribe(d=>this.print('One sees '+d)); // <-----
  else this.subscriptions.one.unsubscribe();
}
like image 141
Thierry Templier Avatar answered Sep 12 '26 17:09

Thierry Templier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!