Use the map operator instead of firing events on a Subject

André Staltz
InstructorAndré Staltz
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 6 years ago

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.

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

[00:21] 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.

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

[00:53] 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.

[01:07] 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.

[01:22] 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.

[01:35] 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.

[01:54] 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.