2017-02-20 4 views
1

RxJSでは、すべての新しいサブスクライバに最後に発行されたアイテムを与えたいと思います。しかし、Observableチェーンではどうしたらいいですか?最後に発行されたアイテムを各サブスクライバに「再生」する方法は?

一つの方法は、publishReplayを使用することです:

this.http 
    .get() 
    .map() 
    .publishReplay(1) 
    .refCount(); 

ソースが完了源、(ある場合

this.http.get().map().replaySubject().refCount()

答えて

2

この回答はRxJS 5を指し、応答が受信された後に完了してからのrest-callの典型的なものです)、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 
} 

あなたの成分(複数可)のことができます現在 "キャッシュされている"データを取得する場合はmyData$.subscribe(...)、最新のデータを取得する場合はrequestData().subscribe(...)を介してデータを取得してください。

関連する問題