Cache data using observable in angular

Varun Dhamija
1 min readJul 30, 2018

--

While using observables , you can use the following approach to cache data:

Let’s take a code example,

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Observable, ReplaySubject } from 'rxjs';

@Injectable()
export class CachedService {
data$: Observable<Response> = this.replaySubject.asObservable();

private replaySubject= new ReplaySubject<Response>(1);

constructor(private http: Http) { }

fetch() {
this.http.get(...).subscribe(data =>
this.replaySubject.next(data));
}
}

Here, I have defined a data$($ as a suffix basically represents a stream of values) variable of Observable type and assigned replaySubject to it. Then, I have defined a ReplaySubject variable. ReplaySubject replays the earlier values. So, this is the class through which we implement caching using observables in angular.

@Component({ ... })
export class SomeOtherComponent implements OnInit {

constructor(private cachedService: CachedService) { }

ngOnInit() {
this.cachedService.fetch();
this.cachedService.data$.subscribe(...);
}
}

So, when you call fetch method, it will make a new http call and any subscribers to this method will get the new updated data whereas any subscribers to cachedService.data$ will get response from the ReplaySubject . It replays the earlier values and any subscribers to it will always get the previous response even after a new http call resolves.

So, if you want to get updated data everytime, you just call the fetch method to make a new http call and all its subscribers will be updated once the new data arrives.

Thanks.

--

--