RXJS Operators
RxJS, the popular library for reactive programming using observables, has recently released a new version that includes a number of powerful new operators. In this post, we’ll take a look at some of the most exciting ones and show you how to use them in your own code.
First, let’s start with the pipe operator, which allows you to combine multiple operators into a single function that can be easily composed and re-used. This is a great way to make your code more modular and easier to read. Here’s an example:
import { map, filter, reduce } from ‘rxjs/operators’;
function squareAndFilterOdd(values) {
return values.pipe(
map(val => val * val),
filter(val => val % 2 === 1)
);
}
const values = of(1, 2, 3, 4, 5);
const squaredAndFiltered = squareAndFilterOdd(values);
// Output: 1, 9, 25
Another operator that’s worth mentioning is the switchMap operator, which is a combination of the switch and map operators. It allows you to switch to a new inner observable each time the source observable emits a new value. This is useful for cases where you want to cancel the previous inner observable and start a new one each time the source observable emits. Here’s an example:
import { switchMap } from ‘rxjs/operators’;
const source = of(‘a’, ‘b’, ‘c’);
const result = source.pipe(
switchMap(val => getDataForValue(val))
);
// If the source emits ‘a’, ‘b’, and then ‘c’, the result observable
// will switch to the observable returned by getDataForValue(‘a’),
// then switch to the observable returned by getDataForValue(‘b’),
// and then switch to the observable returned by getDataForValue(‘c’)
Finally, let’s take a look at the withLatestFrom operator, which allows you to combine the latest value from one observable with the current value of another observable. This is useful for cases where you want to use the latest value from one observable to calculate the current value of another. Here’s an example:
import { withLatestFrom } from ‘rxjs/operators’;
const source1 = of(1, 2, 3);
const source2 = of(‘a’, ‘b’, ‘c’);
const result = source1.pipe(
withLatestFrom(source2),
map(([val1, val2]) => val1 + val2)
);
// The result observable will emit ‘1a’, ‘2b’, and ‘3c’
These are just a few of the many new operators that have been added in the latest version of RxJS. To learn more about them and see more examples of how to use them, be sure to check out the official RxJS documentation.