In Web development, you often deal with stream of data passed over time using Observables. (I have discussed about observables in my last blog post). However in most scenarios, you will find that you cannot simply consume the data directly, you will need to manipulate the data in someway using functions.
RxJs provides operators for this purpose. Tap, Map and SwitchMap are three such popular operators to apply functions over the observable data. All the three operators have different purpose and utility to them. I will discuss them briefly.
Tap is perhaps the most simplest of all the three operators. Tap takes a callback function as an input. It then applies that function on each value in the stream.
Tap is used when you want to have a side effect on the data but not manipulate the data. It takes an observable stream and returns the same observable in return. It is commonly used for logging and debugging.
const observableData = of(1,2,3);observableData.pipe(
tap(item => console.log(“Value:“+item)))//Outputs:“value:1”...
.subscribe(console.log(value)); //Outputs : 1,2,3.Values not changed
Map is similar to Tap when you consider that they both apply a method on a stream of data. But here is the fundamental difference.
Map doesn’t return the original observable back. Instead it takes data, transforms the data and then returns this transformed data back. Map is usually used when you want to process the original data and transform it.
switchMap is an operator that “switches” to a new observable discarding the previous observable. Here is how it works, switchMap takes an observable value, it then maps the value to a new inner observable and returns values from this new observable. The previous observable no longer exists.
The below example illustrates this in a better way.
You can see that the subscribe is now subscribed to the new observable. switchMap is most commonly used when you want to subscribe to an observable which is mapped to data from an outer observable. For example, you may want to call an api and pass the item as an argument to that api.
Hope you enjoyed the reading.