Debugging an Observable Stream
Let's see how we can manage and debug observable streams by using 'tap', 'toArray', and 'repeat' operators.
Debugging streams
The inner observable keeps things simple when it comes to managing the split data, but it creates a bit of a mess in the middle of our previously debuggable observable flow.
Debugging was easy when there was only one observable (when we could just add .subscribe(console.log)
at the point of contention and comment out the rest).
Now there are multiple observable chains kicking around (and one of them doesn’t even have an explicit subscribe). How can we peek into a running observable chain to see what’s going on?
📝
mapTo
andmergeMapTO
Sometimes, we want to convert each element in a stream to a new value but don’t really care about the current value of the event. Rx provides
mapTo
for just this purpose:
interval(1000)
.pipe( mapTo('Hello world!') )
.subscribe(console.log); // logs 'Hello world!' every second
mergeMapTo
also exists, allowing you to pass in any unwrappable item. Here, the button click event doesn’t carry the information we want; all that matters is firing off a request to thelogout
endpoint.mapTo
wouldn’t work here, because it won’t subscribe to the observable (which triggers the request):
fromEvent(myButton, 'click') .pipe( mergeMapTo(ajax('/logout')) ) .subscribe(console.log);
These two operators are most useful when the presence of an event in the stream signifies something’s happened, but the event doesn’t carry any useful information.
Get hands-on with 1400+ tech skills courses.