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.


    Replace Observable.create with Observable creation helpers


    In this lesson we will learn about potential problems that may arise when using Observable.create, a low-level function for creating Observables. In its place, we will use easier helper functions that create Observables in a safe manner.



    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




    With observable.create we can control what happens when we subscribe to the observable and what happens when we unsubscribe. That said, you usually don't need observable.create. Because it's very low-level, we took a lot of lines of code here just to get an observable of clicks.

    Also, because it's low-level as well, here we are facing potential problems, for instance when we call What if we would have made a typo where we have an extra V here for the name? Then this would throw an error.

    But we need to catch the error and send it to the observer as well. Ideally we need to write like this. Try and then catch the error and then send that error as well to the observer. We need to do this because who knows?

    Maybe some other operators down the chain will try to catch this error, or replace it, or something like that. As you can see, we need even more code to get it all correct. Instead of using observable.create, RX provides a lot of helpers to create observables of different types.

    It happens to be for events on the dom such as clicks, we already have a helper called observable.fromEvent and here we can pass the node or the element and here we're going to pass the document and events of type click.

    With this, we get the same thing that we had before and it already has that unsubscription logic to remove event listeners and so forth. It still works as we want it to, and etc. Of course, fromEvent doesn't work for all of the types of observables. Of course, if you want something from WebSockets, for instance, you're not going to use fromEvent. You're going to use something else.

    But RX has many of these helpers to create observables and you should try to use them as much as possible instead of resorting to observable.create, because it's very low-level and you may do something wrong or forget some small detail. Usually you can get by creating all of the observables that you need from these helpers.