Reputation: 21638
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?
Upvotes: 7
Views: 5435
Reputation: 9331
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 :)
Upvotes: 10
Reputation: 9800
For rxjs 6.x.x (tested with 6.5.4), we need to add the pipe() function like this:
myService.getStuffFromServer()
.pipe(
map(functionThatManipulatesData),
flatMap(manipulatedData =>
myService.getMoreStuffFromServer(manipulatedData)))
.subscribe(moreData => {
doStuffWithMoreData(moreData);
});
To get it to work correctly.
Upvotes: 0
Reputation: 11
myService.getStuffFromServer()
.subscribe(data => {
let manipulatedData = functionThatManipulatesData(data);
return myService.getMoreStuffFromServer(manipulatedData);
})
.subscribe(moreData => {
doStuffWithMoreData(moreData);
});
Upvotes: -6