3

In RxJS I want to give every new subscriber the last item that was emitted. But how do I do that in an Observable chain?

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

user2864740
  • 60,010
  • 15
  • 145
  • 220
Arlen Beiler
  • 15,336
  • 34
  • 92
  • 135

1 Answers1

5

This answer refers to RxJS 5:

One way would be to use publishReplay:

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

If your source is a source, that completes (which would be typical for a rest-call, since it completes after a response is received), you could also use publishLast:

this.http
  .get()
  .map()
  .publishLast()
  .refCount();

And a third way (which gives you the most flexibility) would be to use an external BehaviorSubject or a 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
}

In your component(s) you can the get the data via myData$.subscribe(...) for getting the currently "cached" data or via requestData().subscribe(...) for the latest data.

Graham
  • 7,431
  • 18
  • 59
  • 84
olsn
  • 16,644
  • 6
  • 59
  • 65