DEV Community

Deborah Kurata
Deborah Kurata

Posted on

Inner Observables and Higher Order Mapping

When first starting out with RxJS, I didn't know what an "inner Observable" was, which made it difficult to fully understand the RxJS documentation. So, what is an inner Observable?

image

When working with Observables, the Observable we are acting on is the outer Observable. The this.categorySelected$ Observable in the above example is an "outer Observable". We can pipe its emitted items through a pipeline of operations using the pipe method.

If any of those operations return an Observable, that returned Observable is the "inner Observable". The http get request in the above example is an "inner Observable".

In our code, we subscribe to the declared Observable, products$ in this example, either with an explicit subscribe or with the async pipe in our template. Subscribing to the declared Observable automatically subscribes to the outer Observable, which is this.categorySelected$ above.

But how do we subscribe to the inner Observable? How do we unsubscribe?

One option is to do something like this:

// Anti-Pattern!
this.sub = this.categorySelected$.subscribe(catId=>
  this.http.get<Product[]>(`${this.url}?cat=${catId}`)
    .subscribe(result => this.products = result)
);

Enter fullscreen mode Exit fullscreen mode

In the above code we explicitly subscribe to the outer Observable. Within the next function passed into the subscribe, we subscribe to the inner Observable. We can use this.sub to unsubscribe from the outer Observable, but using the above code, we have no way to unsubscribe from the inner Observable.

This type of code, with nested subscribes, is not recommended. It is often defined as an "anti-pattern", that is a pattern of code that is not recommended and should be refactored.

So how do you subscribe to those inner Observables? That's the purpose of the RxJS higher-order mapping operators. We'll cover three of the common higher-order mapping operators in upcoming posts:

  • concatMap
  • mergeMap
  • switchMap

All the best!

Top comments (1)

Collapse
 
anandu06 profile image
anandu06

Clean and simply explained ,please post for other operators also , looking forward.