[Vue-rx] Cache Remote Data Requests with RxJS and Vue.js

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()
    );
复制代码

 

posted @   Zhentiw  阅读(434)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-07-19 [Javascript] Use Number() to convert to Number if possilbe
2016-07-19 [Ember] Creating Your First Ember.js Project with Ember-CLI
点击右上角即可分享
微信分享提示