1
在RxJS中,我希望爲每個新訂戶提供最後發佈的項目。但是我如何在一個可觀察鏈中做到這一點?如何「重播」最後發射的物品給每個用戶?
this.http.get().map().replaySubject().refCount()
在RxJS中,我希望爲每個新訂戶提供最後發佈的項目。但是我如何在一個可觀察鏈中做到這一點?如何「重播」最後發射的物品給每個用戶?
this.http.get().map().replaySubject().refCount()
這個答案是指RxJS 5:
一種方法是使用publishReplay
:
this.http
.get()
.map()
.publishReplay(1)
.refCount();
如果源是源,即完成(這是典型的休息呼叫,因爲它在收到響應後完成),你也可以使用publishLast
:
this.http
.get()
.map()
.publishLast()
.refCount();
而第三種方式(它給你最大的靈活性)將使用外部BehaviorSubject
或ReplaySubject
:
public myData$: BehaviorSubject<any> = new BehaviorSubject(null); // initial value is "null"
public requestData(): BehaviorSubject<any> {
this.http
.get()
.map()
.do(data => this.myData$.next(data))
.subscribe();
return this.myData$.skip(1); // the returned subject skips 1, because this would be the current value - of course the skip is optional and depends on the implementation of the requesting component
}
在你的份(S),你可以通過myData$.subscribe(...)
獲取當前「緩存」數據的數據或通過requestData().subscribe(...)
獲取最新數據的數據。