MDK
MDK

Reputation: 505

Cache Data and Update Observable

I'm trying to respond from a service in my Angular application with the Cached data but also trigger a request to update the when subscribed to. I have tried

cache : Observable<any> = this.http.get<any>(ENDPOINT).pipe(shareReplay(1));

getData() : Observable<any>{
  return this.cache;
}

The problem appears to be that the shareReplay blocks further subscriptions. I'm pretty sure I can do this by creating Observables with logic built in but was hoping there may be a streamlined way with the standard operators.

EDIT

The below code provides the desired result, There may be a more elegant way however

cache : ReplaySubject<any> = new ReplaySubject<any>(1);

getData() : Observable<any>{
  this.http.get<any>(ENDPOINT).pipe(first()).subscribe(x=>cache.next(x));
  return this.cache
}

Upvotes: 0

Views: 785

Answers (1)

molysama
molysama

Reputation: 107

I think shareReplay more used to prevent repeated requests, you can use ReplaySubject or BehaviorSubject.

---Edit ---

I'm sorry I mistook your intentions, shareReplay should be able to cache data, the only problem is that new requests cannot be regenerated.

Upvotes: 1

Related Questions