如何解决如何使用 redux obervable 史诗实现 IndexedDB-Then-Network 策略?
我正在开发基于 react-redux-redux-observable 的 PWA,并尝试向应用添加离线功能。
在尝试确定哪种缓存策略适用于我的用例时,Cache-Then-Network 似乎是最佳选择,因为我需要即时响应和新鲜数据。离线食谱博客中的代码片段简单明了:
var networkDataReceived = false;
startSpinner();
// fetch fresh data
var networkUpdate = fetch('/data.json')
.then(function (response) {
return response.json();
})
.then(function (data) {
networkDataReceived = true;
updatePage(data);
});
// fetch cached data
caches
.match('/data.json')
.then(function (response) {
if (!response) throw Error('No data');
return response.json();
})
.then(function (data) {
// don't overwrite newer network data
if (!networkDataReceived) {
updatePage(data);
}
})
.catch(function () {
// we didn't get cached data,the network is our last hope:
return networkUpdate;
})
.catch(showErrorMessage)
.then(stopSpinner);
service-worker.js
self.addEventListener('fetch',function (event) {
event.respondWith(
caches.open('mysite-dynamic').then(function (cache) {
return fetch(event.request).then(function (response) {
cache.put(event.request,response.clone());
return response;
});
}),);
});
但是,我想将第一个代码片段转换为 action-reducer-epic 格式,同时从 indexedDB(使用 Dexie 库)获取缓存数据。目前,获取数据史诗看起来像这样:
const fetchDataEpic = (action$) => action$.pipe(
ofType('FETCH_DATA'),mergeMap(() =>
ajax.get('some url').pipe(
map(response => response.response)
).pipe(
map(data => of({ type: 'FETCH_DATA_RECEIVE' })),catchError(error => of({ type: 'FETCH_DATA_ERROR' }))
)
)
);
我探索了使用 forkJoin 的可能性,但由于它在所有内部 observables 完成时发出,所以它不可能是正确的选择。
寻求帮助,因为 rxjs 很难掌握,而且相关示例很少。
- react v16.9
- rxjs v6.3.3
- redux-observable v1.0.0
- react-redux v5.0.7
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。