After once again being stunned by the wonder of Observables (and RxJS) I decided to reflect on my 3 most used and valuable Observable operations.
1. forkJoin:
Observable.forkJoin(dressMeService.getHat('winter'),
dressMeService.getScarf('winter'),
dressMeService.getJacket('winter'),
dressMeService.getBoots('winter'))
.subscribe(data => {
const [hat, scarf, jacket, boots] = data;
this.dressMe(hat, scarf, jacket, boots);
this.goOutside();
});
The forkJoin operation allows you to call upon a group of observables and not return till they have all resolved. This is probably our most used operation, as most often you need all your data at once for a view.
Obviously the above example is contrived and you should probably design your backend to deliver an entire outfit based on the season, however you can see the benefit of the forkJoin in consolidating calls to services and improving code quality.
2. flatMap:
const outfitOBservable = weatherService.checkTheWeather('today')
.flatMap(weatherResult => {
return dressMeService.getOutfitForWeather(weatherResult);
});
A flatMap is essentially a daisy chain operation. The above code snippet returns an Observable of type ‘Outfit’, i.e. Observable
3. concat:
shirts = [new Shirt('blue'), new Shirt('red'), new Shirt('green')]
Observable.concat(
clothesService.ironShirts(shirts),
clothesService.foldShirts(shirts),
);
For those of us coming from a C# background (or other programming languages with the ‘async’ operator), it can be frustrating when you need to run several async calls that do not need to share any data (so need for flatMap), however the order of the calls matter. In C# you would just line the calls up neatly with the ‘await’ operator and be done with it.
RxJS has saved the day with ‘concat’. The concat operator runs the above calls in the order presented. So in the above example it will first ‘ironShirts’ and once that has resolved it will move on to ‘foldShirts’. Obviously you can’t fold your shirts till they are ironed right?