EDIT July 2022: The original solution worked only with now deprecated operators and was asctually based on a bug in RxJS. For an up to date solution see the updated aswer here Temporarily caching HTTP responses from parametrised requests using RxJS (and Angular).
ORIGINAL ANSWER: This is what I use to show off RxJS. The following example caches the latest mocked HTTP response for 1 second. It's based on RxJS multicasting via publishReplay()
and refCount()
.
var counter = 1;
var updateTrigger = Observable.defer(() => mockDataFetch())
.publishReplay(1, 1000)
.refCount()
.take(1);
function mockDataFetch() {
return Observable.of(counter++)
.delay(100);
}
function mockHttpCache() {
return updateTrigger;
}
mockHttpCache().toPromise()
.then(val => console.log("Response from 0:", val));
setTimeout(() => mockHttpCache().toPromise()
.then(val => console.log("Response from 200:", val))
, 200);
setTimeout(() => mockHttpCache().toPromise()
.then(val => console.log("Response from 1200:", val))
, 1200);
setTimeout(() => mockHttpCache().toPromise()
.then(val => console.log("Response from 1500:", val))
, 1500);
setTimeout(() => mockHttpCache().toPromise()
.then(val => console.log("Response from 3500:", val))
, 3500);
See live demo: https://jsbin.com/todude/3/edit?js,console
This prints to console:
Response 0: 1
Response 50: 1
Response 200: 1
Response 1200: 2
Response 1500: 2
Response 3500: 3