Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect rxjs related memory leaks in Angular apps

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.

like image 416
robert Avatar asked Feb 12 '19 21:02

robert


People also ask

How do you check if there is a memory leak in angular?

The first thing to do is to open the Chrome Dev Tools, open the panel on the right and click on More Tools > Performance Monitor. The memory of our application is displayed in the blue graph.

What can be done to monitor the memory usage in angular?

You can type window. performance. memory in the devtools console and it will show you the memory usage. Now type it no matter where in your angular application, it will produce typescript error, so it wont compile your code.

How do you detect a memory leak in Web application?

Start with metrics such as page load times, HTTP request times, and Core Web Vitals – time to the first byte, first contentful paint. If you use Sematext Experience you'll see a number of other useful metrics for your web applications and websites there. However, metrics themselves are only a part of the whole picture.


1 Answers

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.

like image 133
André Werlang Avatar answered Oct 14 '22 22:10

André Werlang