How to detect rxjs related memory leaks in Angular apps

后端 未结 1 544
醉酒成梦
醉酒成梦 2021-02-01 04:45

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

Just recently discovered a pretty nasty memory leak where com

1条回答
  •  心在旅途
    2021-02-01 05:35

    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.

    0 讨论(0)
提交回复
热议问题