Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to chain observables in Angular?

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?

like image 898
Adrian Brand Avatar asked Jul 07 '17 10:07

Adrian Brand


1 Answers

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 use flatMap.

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 :)

like image 116
Vamshi Avatar answered Nov 09 '22 15:11

Vamshi