Observables Returning Observables
Learn how to create a new Observable stream for each Observable value in a stream using the mergeMap operator.
We'll cover the following
Creating a new Observable while already handling one
Quite often, when working with Observables, we need to return a new Observable stream while already dealing with an Observable stream. In other words, for each Observable value in a stream, create a new Observable stream.
While this might sound complicated, in the real world, it can happen fairly regularly. Suppose that we are working with a REST API that tells us what products are sold within a sales catalog. This particular API call returns an array of product IDs that are associated with a particular catalog. For each of these product IDs, we then need to initiate a new REST API call to retrieve the information for this particular product, such as its name and description.
Let’s assume that we are using an HTTP client that returns an Observable for each API call. This means that the first Observable stream will be the list of products within a catalog, say, [1,2,3]
.
For each value in this stream, we then need to initiate a new API call to fetch the name and description for the product, which will also return an Observable.
So, while dealing with each value of the original Observable stream, we then need to deal with another Observable stream that contains the product details.
To illustrate this concept, consider the following interfaces:
Get hands-on with 1200+ tech skills courses.