Memory leak when using app level event to update a TableView

You must Login before you can answer or comment on any questions.

I have a TableView I want to update when an item is added to the database. Using app level events for the TableView to be notified causes a memory leak.

I remove the event listener when the window closes, but this doesn't help.

This is a much-discussed issue, and is even covered in a CodeStrong session, but I have not seen a solution or workaround. What can be done to prevent the memory leak? Is there a better solution for a TableView to be reloaded based on an event?

var listener = function(e) {
     // reload tableview
     ...
     <snip>
     ...
     tableView.setData(data);
};
 
Ti.App.addEventListener('database_event', listener);
 
win.addEventListener('close', function(e) {
     Ti.App.removeEventListener('database_event', listener);
});

1 Answer

Hi Josh. I think the problem is not in app-level events (although, IMHO you should avoid using them in most cases), the problem is that "listener" is a global variable holding function reference (that is ... event listener function). So, when you remove event listener, that function still exists because it's referenced by "listener" global variable, therefore table view component won't be garbage collected because "tableView" variable still holds reference to it. Try to set "listener" to "null" after you remove app-level event to see if that solves the issue.

— answered 2 years ago by Ivan Škugor
answer permalink
1 Comment
  • Ah, now I see that I made a mistake, although I was on a good trace. The actual problem is "tableView" variable, which I think is global variable that holds reference to TableView component (that code is not visible, but from context it seems that's the case). Try to set those variable to null in window's close event.

    — commented 2 years ago by Ivan Škugor

Your Answer

Think you can help? Login to answer this question!