Join egghead, unlock knowledge.

Want more egghead?

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

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Switch to a Function which Creates Observables with Vue.js and Rxjs

    5.5.12 - 6.4.0

    Wrapping the creation of an Observable inside of a Function allows you delay the creation of the Observable until it is needed. This becomes really important when the Observable is created from a Promise due to the way Promises execute on creation.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    Instructor: You'll notice on the initial page load, if I refresh here, you will see that it automatically loads in this Luke Skywalker data even though I haven't clicked anything yet. That's because my promise here is being invoked and executing even though I haven't clicked, because this function is executed inside of this observable.

    The way to defer that is I'll extract this and just call it URL. Then say this URL is an argument, which returns an observable. That means that, instead of this being a stream, this would be a function which I'll name CreateLoader. This can be CreateLoader, and then I could paste the URL in there. You'll see, when I click, everything loads fine.

    Rather than pasting it in there, what I want to do is extract it even further up. I'll say URL, and then the switch map will take URL, because I'll want to map these clicks to that URL. Now if you look at it, I'll click, and that maps to a string. That string is passed to a switch map, which creates the loader.

    I'll click, and then it loads in just fine, because this function takes one argument, there's one argument there, and it's passed in there. We can even delete this here, delete this here, make sure that's closed off, and click. Everything works the exact same way. Now when we open up the network tools, when I refresh, you won't see any initial request for that data, because it's not loaded until you click.