If I have a service call that relies on the result of another service call what is the best way to chain them?
myService.getStuffFromServer().subscribe(data => {
let manipulatedData = functionThatManipulatesData(data);
myService.getMoreStuffFromServer(manipulatedData).subscribe(moreData => {
doStuffWithMoreData(moreData);
});
});
Is the way I have been doing it but the nesting gets a bit messy sometimes. Is there a cleaner way?
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With