What is the best way to chain observables in Angular?
As mentioned in the comments its very simple.
myService.getStuffFromServer().
.map(functionThatManipulatesData)
.flatMap(myService.getMoreStuffFromServer)
.subscribe(doStuffWithMoreData);
map
transforms each element of a stream from one type of data to another. But if that transformation involves an asynchronous call we useflatMap
.
Most simple way I can describe and this thinking helped me a lot.
We can use flatMap
also to add more than one item to the stream. For example , map takes one item and replaces that with new item. What if we want to take one item and add 3 items in its place . For example I want to replace a number with its square and cube too .
----1---2---3---
to
----1---1---1---2---4---8---3---9---27----
Then we can use flatMap
stream.flatMap(num => Observable.of(num, num*num, num*num*num));
Now flatMap replaces each element with three new elements. These are two important functionalities of flatmap. Hope I confused you enough :)