RxJS: Don’t Unsubscribe Anymore thanks to Rx-Scavenger, the RxJS Garbage Collector
You are probably used to one of the following common approaches :
- Keep subscriptions in properties and unsubscribe manually (i.e. : in
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.
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:
Scavenger is handed a reference to the component and thus it will automagically implement the
ngOnDestroy method for you.
Scavenger.collect() operator, the
Scavenger will collect every subscription and unsubscribe it on
ngOnDestroy or when asked for by calling
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
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.