Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Share RxJS Streams to Avoid Multiple Requests in Vue.js

    John LindquistJohn Lindquist

    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.

    vueVue.js
    ^2.0.0
    rxjsRxJS
    ^5.0.0
    javascriptJavaScript
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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...

    Discuss

    Discuss