這是我用來炫耀RxJS。以下示例將最新的模擬HTTP響應緩存1秒。它基於RxJS多播通過publishReplay()
和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);
見現場演示:https://jsbin.com/todude/3/edit?js,console
這將打印到控制檯:
Response 0: 1
Response 50: 1
Response 200: 1
Response 1200: 2
Response 1500: 2
Response 3500: 3
OK,我現在讓我的錯誤。我可以使用'publishReplay'和'refCount',但是如果我沒有訂戶,我可能會錯過/跳過一些底層序列值。 我之後立即調用了'subscribe'來解決這個問題,但我想這不是一個好的解決方案。 –
我在SO文檔中發佈了一篇文章,詳細解釋它是如何工作的:http://stackoverflow.com/documentation/rxjs/8247/common-recipes/26490/caching-http-responses#t=201612161544428695958 – martin