⚠️ This lesson is retired and might contain outdated information.

Share RxJS Streams to Avoid Multiple Requests in Vue.js

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

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.

Instructor: [00:00] you'll also notice in the network tab when I click, you'll see two requests going out and loading the same data. The reason that's happening is because Luke is here and here, so this pluck name stream and this pluck map stream, which are named here for name and load image are both telling this stream, this Luke stream, to trigger that request.

[00:25] When you have two streams which are accepting values from a single stream and you want them to stay in sync, then simply tack on a share at the end here. I'll hit Save, clear out the network tab, and click. You'll see it only made this one request this time. That's because each stream that's being attached to this Luke stream is now sharing that same initial stream.

[00:52] This load request will be shared between the name stream and the load image stream. You'll want to make sure to put this after something like a heavy request is made. If I put this up where the click is made, it's only sharing that initial click.

[01:09] If I clear out the network tab and click, you'll see it's still making those two requests, because this is being shared here, but everything underneath it is still being requested twice by these two streams.

[01:21] Make sure to share at the point in the stream where you know the other streams are going to want that same data, that data being that request, so when I click once, you make one request...