Moshe Shaham
Moshe Shaham

Reputation: 15974

Observable with cached data and server refresh

i have a component that gets data from a service. the data is first served from cache, if it exists, and in the background makes an http request to update the data. i understand i can call next twice and it will work. like this:

  getTickets() {
    this._subject.next(this.getTicketsFromCache());
    this.serverService.getAllTickets()
      .subscribe((getAllTicketsResponse: GetAllTicketsResponse) => {
        this._tickets = getAllTicketsResponse.Result.tickets;
        this._subject.next(this._tickets);
      });
    return this._subject;
  }

but my question is how can the component know that this is from cache? i need to display a loading icon while it is refreshed, and hide it when it ends. how do i do that?

Upvotes: 0

Views: 166

Answers (1)

Tomasz Błachut
Tomasz Błachut

Reputation: 2507

Instead of passing bare value pass object { value, isLoading }

getTickets() {
    this._subject.next({
        value: this.getTicketsFromCache(),
        isLoading: true,
    });
    this.serverService.getAllTickets()
        .subscribe((getAllTicketsResponse: GetAllTicketsResponse) => {
            this._tickets = getAllTicketsResponse.Result.tickets;
            this._subject.next({
                value: this._tickets,
                isLoading: false,
            });
        });
    return this._subject;
}

and handle additional logic in component

Upvotes: 2

Related Questions