Skip to main content
rewrite answer, to match question according to comment.
Source Link
Bogdan Savluk
  • 6.3k
  • 1
  • 32
  • 37

You can easily construct it using RxJS interval and flatMapTo implement this, you will need to create your own observable with custom logic on subscribtion:

Observablefunction createTimedCache(doRequest, expireTime) {  let lastCallTime = 0; let lastResult = null;  const result$ = new Rx.intervalSubject(60000);    return Rx.flatMap(Observable.create()observer => this{ const time = Date.restServicenow(); if (time - lastCallTime < expireTime) { return (lastResult // when result already received ? result$.getstartWith('lastResult) /information/' still waiting for result : result$ ).subscribe(observer);   } const disposable = result$.cachesubscribe(1observer); lastCallTime = time; lastResult = null; doRequest() .do(result => { lastResult = result; }) .subscribe(v => result$.next(v), 60000e => result$.error(e)); return disposable; }); } 

It will update cached data, and emit it to all subscribers every 60 seconds, and will stop doing that when last one unsubscriberesulting usage would be following:

this.information = createTimedCache( () => this.restService.get('/information/'), 60000 ); 

usage example: https://jsbin.com/hutikesoqa/edit?js,console

You can easily construct it using RxJS interval and flatMap:

Observable .interval(60000) .flatMap(() => this.restService.get('/information/')) .cache(1, 60000); 

It will update cached data, and emit it to all subscribers every 60 seconds, and will stop doing that when last one unsubscribe

To implement this, you will need to create your own observable with custom logic on subscribtion:

function createTimedCache(doRequest, expireTime) {  let lastCallTime = 0; let lastResult = null;  const result$ = new Rx.Subject();    return Rx.Observable.create(observer => { const time = Date.now(); if (time - lastCallTime < expireTime) { return (lastResult // when result already received ? result$.startWith(lastResult) // still waiting for result : result$ ).subscribe(observer);   } const disposable = result$.subscribe(observer); lastCallTime = time; lastResult = null; doRequest() .do(result => { lastResult = result; }) .subscribe(v => result$.next(v), e => result$.error(e)); return disposable; }); } 

and resulting usage would be following:

this.information = createTimedCache( () => this.restService.get('/information/'), 60000 ); 

usage example: https://jsbin.com/hutikesoqa/edit?js,console

Source Link
Bogdan Savluk
  • 6.3k
  • 1
  • 32
  • 37

You can easily construct it using RxJS interval and flatMap:

Observable .interval(60000) .flatMap(() => this.restService.get('/information/')) .cache(1, 60000); 

It will update cached data, and emit it to all subscribers every 60 seconds, and will stop doing that when last one unsubscribe