This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Replace Observable.create with Observable creation helpers

    André StaltzAndré Staltz

    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.

    rxjsRxJS
    ^5.0.0
    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

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

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

    00:32 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?

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

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

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

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

    Discuss

    Discuss