One of the must tricky parts in Angular (or simply when using RxJS in general) is to handle
Subscriptions; but don’t panic!
There are many ways to handle this properly and we’ll show you around the most common approaches.
async Pipe, it is possible to let Angular handle the subscription and unsubscribe when the component is destroyed (or simply when the element is destroyed using a structural directive like
*ngIf for example).
This can get tricky as multiple subscriptions might trigger the same processing multiple times and that’s when we need some operators like
shareReplay which will connect once to the
Observable and share the same data with all subscribers.
The view is not the only final subscriber. Sometimes you will want to handle
Observables programmatically from your
In order to handle errors and completions you will probably need to use some extra operators like
last and sometimes, things might get tricky.
The other trick is to use the
takeUntil operator on every
Once notified (we’ll be using a Subject) by
takeUntil will unsubscribe all opened
A bit verbose and thus error-prone.
startCounting() method multiple times will create a race condition and turn our component into a crazy counter. We should unsubscribe from the previous
Rx-Scavenger is an RxJS Subscription Garbage Collector specially made for Angular (but it works in other contexts too).
It is aiming to:
- reduce the boilerplate code needed to handle
- handle subscription replacement in order to avoid race conditions like the one described above.
As you can see below, we give the instance of the component to the
Scavenger and it takes care of generating all the (subject and
ngOnDestroy) code we’ve written above with
… but wait!!! We still didn’t handle the subscription replacement issue when calling
startCounting() multiple times.
In order to fix that issue, we just have to replace
collect() method by
collectByKey(key: string) method and give it some unique key that represents the operation.
Now, every time we call this method, the previous
Subscription is unsubscribed from automagically before subscribing to the new one.
Give it a try and let us know how it worked for you 😉