Tutorial hero
Lesson icon

Higher Order Observables

Originally published August 18, 2022 Time 2 mins

Higher-order observables… outer observables… inner observables… they sound scary, but are simpler than they sound. These were the concepts in RxJS that always confused me the most.

A higher-order function sounds way fancier than it is. The basic idea is that a high-order function does either of these things (or both):

  • Accepts a function as a parameter
  • Returns a function

It’s a function that returns a function, or accepts a function. Similarly, a higher-order observable is an observable that returns an observable.

This is where flattening operators like switchMap, concatMap, and mergeMap come into play. As well as the concept of an outer observable and an inner observable.

Consider this example (this is not how you should approach this problem):

example concept of outer and inner obervables

The goal here is to take an observable of URL strings, and return the data from each of those by making an HTTP request.

Our initial attempt here uses a simple map operator to take the URLs and return an HTTP request to that URL instead. The problem is we don’t get the value from that HTTP request returned from the map, we get an observable of that HTTP request.

We are now dealing with higher-order observables - an observable that returns an observable.

This example is awkward, because if we subscribe to it, it is going to give us four observables. We don’t want the observables from the HTTP request, we want the actual data!

This is where the flattening operators like mergeMap come into play. They will take the values emitted from the outer observable (myObservable$), and subscribe to the inner observable (http.get()):

myObservables pipe

The end result is that now instead of being returned a stream of observables, we actually get a stream of the data we want from the HTTP request, because the flattening operator handles subscribing to it and pulling out data for us!

Learn to build modern Angular apps with my course