Disclaimer: I’m the author of the tool I mention below.
This can be accomplished by keeping a list where new subscriptions are added to, and removing subscriptions from this list once it is unsubscribed.
The troublesome part is observing subscriptions. A straightforward way to achieve this is by monkey-patching the Observable#subscribe()
method, that is, replacing the Observable prototype method.
This is the overall approach of observable-profiler, a development tool which hooks into an Observable library (i.e rxjs) and prints leaking subscriptions in console.
A simple way to use the profiler is start tracking once the app is bootstraped, then stop tracking after a time:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { Observable } from 'rxjs';
import { setup, track, printSubscribers } from 'observable-profiler';
setup(Observable);
platformBrowserDynamic([])
.bootstrapModule(AppModule)
.then(ref => {
track();
window.stopProfiler = () => {
ref.destroy();
const subscribers = track(false);
printSubscribers({
subscribers,
});
}
});
Just call stopProfiler()
in devtools console once you want a report.