From 76d0f0d209de5209c476a817b6c37ba459623118 Mon Sep 17 00:00:00 2001 From: piotrpekala7 <31202938+piotrpekala7@users.noreply.github.com> Date: Wed, 19 Feb 2020 15:54:18 +0100 Subject: [PATCH] Basic cache for some of the services --- src/app/services/symbol.service.ts | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/app/services/symbol.service.ts b/src/app/services/symbol.service.ts index fba64d13..cba041d0 100644 --- a/src/app/services/symbol.service.ts +++ b/src/app/services/symbol.service.ts @@ -1,13 +1,17 @@ import { Injectable } from '@angular/core'; -import { BehaviorSubject, forkJoin, Observable } from 'rxjs'; +import { BehaviorSubject, forkJoin, Observable, of } from 'rxjs'; import { Symbol } from '../models/symbol'; import { Server } from '../models/server'; import { HttpServer } from './http-server.service'; +import { shareReplay } from 'rxjs/operators'; + +const CACHE_SIZE = 1; @Injectable() export class SymbolService { public symbols: BehaviorSubject = new BehaviorSubject([]); + private cache: Observable; constructor(private httpServer: HttpServer) {} @@ -16,25 +20,22 @@ export class SymbolService { } add(server: Server, symbolName: string, symbol: string) { + this.cache = null; return this.httpServer.post(server, `/symbols/${symbolName}/raw`, symbol) } load(server: Server): Observable { - const subscription = this.list(server).subscribe((symbols: Symbol[]) => { - const streams = symbols.map(symbol => this.raw(server, symbol.symbol_id)); - forkJoin(streams).subscribe(results => { - symbols.forEach((symbol: Symbol, i: number) => { - symbol.raw = results[i]; - }); - this.symbols.next(symbols); - subscription.unsubscribe(); - }); - }); - return this.symbols.asObservable(); + return this.httpServer.get(server, '/symbols'); } list(server: Server) { - return this.httpServer.get(server, '/symbols'); + if(!this.cache) { + this.cache = this.load(server).pipe( + shareReplay(CACHE_SIZE) + ); + } + + return this.cache; } raw(server: Server, symbol_id: string) {