import { Injectable } from '@angular/core'; import { Observable, ReplaySubject, Subscription, timer } from 'rxjs'; import { catchError, take } from 'rxjs/operators'; import { IItem } from '../models/item'; import { ItemService } from './item.service'; const REFRESH_INTERVAL = 15 * 60 * 1000; // 15m @Injectable({ providedIn: 'root'}) export class CacheService { private proxyCacheMap: { [key: string]: ReplaySubject } = {}; private subscriptionMap: { [key: string]: Subscription } = {}; constructor(private itemService: ItemService) { timer(0, REFRESH_INTERVAL).subscribe(() => { this.subscriptionMap = {}; }) } getItemList(itemType: string) : Observable { if (!this.proxyCacheMap[itemType]) { this.proxyCacheMap[itemType] = new ReplaySubject(1); } if (!this.subscriptionMap[itemType]) { this.subscriptionMap[itemType] = this.itemService.getItemList(itemType) .pipe( catchError(error => { this.subscriptionMap[itemType].unsubscribe(); this.subscriptionMap[itemType] = null; throw error; }), ).subscribe(items => { this.proxyCacheMap[itemType].next(items); }); } return this.proxyCacheMap[itemType].asObservable() .pipe( take(1) ); } }