[Vue-rx] Cache Remote Data Requests with RxJS and Vue.js
2023-09-14 09:00:50 时间
A Promise invokes a function which stores a value that will be passed to a callback. So when you wrap a Promise with an Observable, you'll always get that same value. This enables you to use the behavior as a caching mechanism when the Promises make requests for remote data.
const p = new Promise((resolve, reject )=> { console.log("Promise started"); // This line will be print out only once, when the promise was invoked resolve(new Date()); }); // The output date should be the same, since promise was only invoke once p.then(( date)=> { console.log(date) // Thu Jul 19 2018 12:55:41 GMT+0300 (EEST) }) setTimeout(( )=> { p.then(( date)=> { console.log(date) //Thu Jul 19 2018 12:55:41 GMT+0300 (EEST) }) }, 2000);
Caching data in RxJS can be as simple as creating a caching function which can store the values in an object. This lessons walks through creating a caching function and explains how the function closes over an object then pairs a url with an Observable that returns the resolution of a Promise
let cache = {}; // Cache function const cachePerson = cache => url => cache[url] ? cache[url]: cache[url] = createLoader(url); const activeTab$ = this.$watchAsObservable('activeTab', { immediate: true }).pipe(pluck('newValue')); // this.$http.get() return a promise, then convert to Observable using from() const createLoader = url => from(this.$http.get(url)).pipe(pluck('data')); const people$ = createLoader('https://starwars.egghead.training/people').pipe( map(people => people.slice(0,7 )) ); const person$ = combineLatest( activeTab$, people$, (people$, (tabId, people) => people[tabId].id)) .pipe( map(id => `https://starwars.egghead.training/people/${id}`), switchMap(cachePerson(cache)), catchError(() => of({ name: 'Failed.. :(' })), share() );
相关文章
- MongoVUE_Vue.js+Flask+MongoDB
- 尚硅谷Vue课程P30-P35笔记(后台回复 vue 可获得更多笔记!)
- vue、css修改滚动条样式
- 2022前端经典vue面试题(持续更新中)
- vue项目性能优化-前端加分项
- vue JS 对象转数组[通俗易懂]
- 三年经验前端vue面试记录
- Vue学习笔记之vue.js 两个等号 == 和三个等号===的区别 数字0和空字符串
- 用js在控制台打印html页面,vue 使用print-js 打印html页面
- 瀑布流组件vue-waterfall
- vue-property-decorator的简单介绍,一看就会
- vue.js与jquery的区别_说出两者之间的区别
- VUE组件封装_vue组件内部双向绑定
- Vue.js – 引入外部 JS 文件
- vue 生成二维码 打印_代码生成二维码
- vue-router实现路由懒加载( 动态加载路由 )_前端懒加载原理
- vue 中路径props的传参
- 开心档之Vue.js 样式绑定
- Vue-slot插槽的所有使用方法
- 基于 Vue,使用 D3.js 画一个疫情趋势折线图
- Vue开发、学习笔记,持续记录
- Vue渲染函数该如何使用?有哪些需要注意的地方?
- vue.js入门篇之Vue.js 样式绑定
- 自定义事件在 Vue.js 组件中的应用
- 应用Oracle中的Vue即时技术(oraclevue)
- Vue.js 与MySQL结合,打造高效Web应用程序(vue.js mysql)
- Vue如何连接Redis(vue怎么连接Redis)