Angular 2 和 RxJS 5 Observable.share()

Angular 2 and RxJS 5 Observable.share()

运行 Angular 2 RC4RxJS 5 beta 6,我很难弄清楚为什么我的可观察对象没有在订阅者之间共享。我试图仔细按照说明进行操作,但无济于事。我的组件在下面,但是你可以看到它 运行 live at this Plunker

模板

<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=[];

输出

自从我使用 .share() 运算符以来,我希望订阅者共享相同的可观察对象。为什么不是?

我认为这是因为每次调用 source 方法时都会创建一个可观察对象。您需要订阅同一个可观察实例。

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