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

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

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 9 months ago

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.

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.

Matt Lindell
Matt Lindell
~ 6 years ago

Sir, could you explain why you are getting 2 request performed when you click once?

xianbo duan
xianbo duan
~ 5 years ago
Markdown supported.
Become a member to join the discussionEnroll Today