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.


    Use the map operator instead of firing events on a Subject

    André StaltzAndré Staltz

    In this lesson we will learn how to replace excessive subscribing and Subject emissions with simple uses of the map operator, simplifying our code and making it less bug-prone.



    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




    Whenever you see a next method inside a next callback when subscribing, then something is wrong. I can't imagine a case where you need this. What's going on here is that we have subject for X coordinates. Whenever a click happens, we want this subject to emit the X coordinate of that click event.

    The way that we're achieving that is by listening to clickstream. We can get those vents of clicks. We feed the client X property into the subject with .next. Now, we have a situation here which data's coming from the clickstream and it's going to the X subject.

    Whenever you have the situation of source of data and then destination, that's exactly the used case for an operator -- getting data from source and sending it to some destination.

    In this case, instead of having this subject, we can make an observable of these X coordinates by using operator on the clickstream. That operator in this case is mapping.

    Usually, when you have a next inside a next, it usually means a map, although there are different cases where you might need a slightly different operator. In this case, we get the click event and we just map that to the property clientX.

    Now, I don't even need the subscribe anymore, because I don't need to get data from clicks. The only purpose of that was to send it into the X subject, but I don't need that anymore.

    We can simply subscribe to the stream of coordinates. Then we can put each of these Xs in the console log. This will work as we want it to. Each time we click, it shows the X coordinate of that event. We don't need the subject here.

    The tip here is if you see a next inside a next, then something is wrong. Remember that we're avoiding subject here, because it's less save by default where observables are often able to automatically dispose resources.