Deborah Kurata
Posted on August 19, 2021
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?
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)
);
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!
Posted on August 19, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.