我需要在不同的时刻绑定到共享可观察量两次。第二个绑定在第一次计算时null
,直到出现下一项。
下面是组件类:
export class App {
subject = new BehaviorSubject(1);
scan = this.subject.scan((current, change) => current + change, 0).share();
other = this.scan.map(item => item);
}
这是模板:
<div>
<button (click)="clickedScan=true">show scan</button>
<button (click)="clickedOther=true">show other</button>
<button (click)="subject.next(1)">next</button>
<div *ngIf="clickedOther">
other | async: <b>{{ '' + (other | async) }}</b>
</div>
<div *ngIf="clickedScan">
scan | async: <b>{{ '' + (scan | async) }}</b>
</div>
</div>
这是Plunker(更新:Plunker更新为接受的答案(
share()
是需要的,因为否则scan
每个订阅者重复调用该方法,但一段时间后完成的下一个async
绑定无法访问最后一个元素。如果不使用share()
所有绑定从一开始就工作,但随后每次调用subject.next()
调用scan
两次(在此 plunker 示例中的单独项实例上(。出于多种原因,我想避免这种重复的scan
调用 - 至少不要为每个订阅者重复完全相同的工作和相同的结果。
我想知道避免多次share
(即使用其他一些Observable
方法(调用并在绑定新async
时仍然提供最后一个元素的正确方法是什么。
是的,您需要一个热可观察量,以便共享订阅而不是拥有单独的订阅。你可能对安德烈的这段视频感兴趣:https://egghead.io/lessons/rxjs-demystifying-cold-and-hot-observables-in-rxjs。您可能还对Paul Taylor在Reactive 2015中的演讲感兴趣:https://youtu.be/QhjALubBQPg?t=385
基本上,您可以像这样重写代码:
import {Subject, ReplaySubject} from "rxjs/Rx"; // only really need these two
/* your other code */
export class App {
// plain old subject for clicks
// i believe you can get an event stream somewhere?
// sorry, i don't know angular2
subject = new Subject();
// replays the last event for observers on subscription
main = new ReplaySubject(1);
// you could apply transforms here if you want
scan = this.main
other = this.main
constructor() {
// take the events that come in
this.subject
// start our observable with an initial event
.startWith(0)
// when subject emits, this will run and update
.scan((current, change) => current + change)
// now we can subscribe our replay subject
.subscribe(this.main);
}
}
希望这有帮助。