How to detect rxjs related memory leaks in Angular apps

人走茶凉 提交于 2019-12-03 05:46:58

问题


Is there any tool or technique to detect "left behind" or "currently alive" observables, subscriptions.

Just recently discovered a pretty nasty memory leak where components were kept alive due to missing "unsubscribe" calls. I read about "takeUntil" approach which seems pretty good. https://stackoverflow.com/a/41177163/2050306

However I'm still wondering is there any tool (browser extension etc.) for that. Augury does not cover this area as far as I know.

All input is greatly appreciated.


回答1:


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.



来源:https://stackoverflow.com/questions/54658614/how-to-detect-rxjs-related-memory-leaks-in-angular-apps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!