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()
        );
  • 相关阅读:
    简单C#、asp.net mvc验证码的实现
    c# 局域网文件传输实例
    c# http get请求与post请求实例
    轻松3步实现c#windowsform窗体美化
    c#内部类的使用
    java
    java
    java
    java
    java
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9331046.html
Copyright © 2011-2022 走看看