Share RxJS Streams to Avoid Multiple Requests in Vue.js

Share this video with your friends

Send Tweet

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.

Paul Perry
Paul Perry
~ 6 years ago

Updated imports for rxjs 6:

import { from, merge, of } from 'rxjs'
import { pluck, switchMap, map, mapTo, catchError, share } from 'rxjs/operators';

Also, the piped version of the updated code to use share looks like this:

const getName$ = this.click$.pipe(
      mapTo("https://starwars.egghead.training/people/1"),
      switchMap( createLoader ),
      catchError(err => of({ name: "Failed :(" }))
    ).pipe(
      share()
    )

This could be broken out into two parts, but to get this example working, it should do for now.

Hope that helps!