RxJS: Don’t Unsubscribe Anymore thanks to Rx-Scavenger, the RxJS Garbage Collector

Younes
Marmicode
Published in
2 min readMay 30, 2018
Rx-Scavenger — RxJS Garbage Collector

If you are an Angular or RxJS user, you are probably tired of handling subscriptions and being worrying about race conditions, memory leaks and CPU time.

You are probably used to one of the following common approaches :

  • Keep subscriptions in properties and unsubscribe manually (i.e. : in ngOnDestroy):
  • Angular’s async Pipe:
  • RxJS takeUntil operator :

Limitations

In some cases, the different approaches described above need a significant amount of boilerplate code and in other cases they can get tricky and error-prone.

For example, calling startCounting() method multiple times will create a race condition and will not produce the expected behavior.

Rx-Scavenger

The last alternative and my favorite one is Rx-Scavenger, the RxJS Subscription Garbage Collector.

First, you’ll have to install it using yarn add @wishtack/rx-scavenger (or npm install --save @wishtack/rx-scavenger ).

Then you can immediately start using in your Angular components like this:

The Scavenger is handed a reference to the component and thus it will automagically implement the ngOnDestroy method for you.

Using the Scavenger.collect() operator, the Scavenger will collect every subscription and unsubscribe it on ngOnDestroy or when asked for by calling Scavenger.unsubscribe() method.

Scavenger.collectByKey or the Killing Feature

We still have an issue here as calling startCounting() multiple times will trigger multiple subscriptions and it’s not the behavior we are looking for.

In order to fix this, we just have to replace this._scavenger.collect() by this._scavenger.collectByKey('count').

collectByKey will make sure that you never have more than one subscription at a time with the same key. So when we call startCounting() a second time, the Scavenger will unsubscribe the previous subscription when subscribing again.

Enjoy!

--

--

Younes
Marmicode

Software Cook, Teacher & Coach Google Developer Expert for Angular Nx Champion