[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()
    );

 

posted @ 2018-07-18 18:50  Zhentiw  阅读(204)  评论(0编辑  收藏  举报