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

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

    John LindquistJohn Lindquist

    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.

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

    00:19 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.

    00:42 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.

    01:04 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.

    Discuss

    Discuss