RxJS 5 and alternatives to the cache operator
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: 1Response 50: 1Response 200: 1Response 1200: 2Response 1500: 2Response 3500: 3