0

I'm developing an application that has a grid of cells where the user can drag objects from 3 containers. The grid is comprised of row components, each of which has 5 cell components for storing the objects. Each cell component subscribes to 2 observables:

  • One is sent when the user modifies the name of an object, so we have to look for all the instances of it in the grid and change its name.
  • The other one is sent when the user wants to search for and highlight an object in the grid.

Also, each cell handles onDragEnter, onDragLeave and onDragDrop events to deal with the dragged objects. We're using OnPush strategy on all the rows and cells, and we call Angular's detectChanges() only when they need to be updated.

We're doing some tests loading grids of 40-50 rows and we've realized that the app performance drops down quite noticeably. I'm pretty sure that the bottle neck comes from all these subscriptions and event handlers so I'm thinking how I could optimize the app.

I'm thinking of using only one subscription for both actions (change name and highlight objects) but I'd also like to know if there's a way to "deactivate" subscriptions when the components are not visible in the browser window and subscribe again when the user scrolls to them.

Has anyone had this scenario in an Angular app? Any ideas are welcome ;)

Thanks,

Fel
  • 4,428
  • 9
  • 43
  • 94

1 Answers1

0

One thing you should definitely do is unsubscribe from all those subscriptions when the component is destroyed.

The main reason to do that is to prevent memory leaks, which are probably the root cause of your app slowing down. There are different ways of doing it, one of the official solutions (and the one I find to be cleaner) is to group all your subscriptions into a Subscription object, and call unsubscribe on that object in your ngOnDestroy rather than unsubscribing all the individual ones one by one.

From the official docs:

Additionally, subscriptions may be grouped together through the add() method, which will attach a child Subscription to the current Subscription. When a Subscription is unsubscribed, all its children (and its grandchildren) will be unsubscribed as well.

You can have a look at this question for a more in depth discussion on the topic.

bugs
  • 14,631
  • 5
  • 48
  • 52
  • Hi! On each component, I have the following code `this.itemSelectedService.getModifiedItem().takeWhile(() => this.alive)` to unsubscribe when they are destroyed (I set `this.alive` to false on the `onNgDestroy` method). I'll have a look at the question you suggested, thanks! – Fel Apr 17 '18 at 08:18