zoukankan      html  css  js  c++  java
  • [Vue-rx] Share RxJS Streams to Avoid Multiple Requests in Vue.js

    Splitting a stream into multiple streams causes new subscriptions. You can think of new subscriptions as "invoking a function". So if your original stream makes a request for data, splitting the original stream will make 2 requests for data. The way to get around this is by using share so that each time the stream is split, all the split stream stay synced together.

    For the RxJS Code below, it issues network reuqest twice:

        const createLoader = url => from(this.$http.get(url)).pipe(pluck('data'));
    
        const luke$ = this.click$.pipe(
          mapTo('https://starwars.egghead.training/people/1'),
          switchMap(createLoader),
          catchError(() => createLoader('https://starwars.egghead.training/people/2'))
        );
    
        const name$ = luke$.pipe(pluck('name'));
    
        const image$ = luke$.pipe(
          pluck('image'),
          map(src => `https://starwars.egghead.training/${src}`)
        );

    Because both 'name$' and 'image$' will trigger 'luke$', then 'createLoader'.

    In order to solve the problem we can use 'share()' or 'shareReplay(1)':

        const luke$ = this.click$.pipe(
          mapTo('https://starwars.egghead.trainin/people/1'),
          switchMap(createLoader),
          catchError(() => createLoader('https://starwars.egghead.training/people/2')),
          share()
        );
  • 相关阅读:
    JS获取浏览器信息及屏幕分辨率
    div + css 让img标签图片在div中等比缩放显示
    java 对于表情和特殊字符的转码解码处理
    VS Code 快捷键设置
    jq 对象获取总结大全
    java Date时间格式工具类DateUtil
    Linux云服务器下Tomcat部署超详细
    文件操作模式
    文件处理
    字符编码
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9331046.html
Copyright © 2011-2022 走看看