Reputation: 3113
Let's say I have many elements and each has its own listener attached to it like so:
DivElement _container = querySelector("#container");
void _createButtons(int count) {
for (int i = 0; i < count; i++) {
var button = new ButtonElement()
..text = "Button #$i";
button.onClick.listen((_) => print("Clicked #$i."));
_container.append(button);
}
}
And then at some point I clear the DOM, like so:
_container.clear();
Should I be worried about the 'orphaned' event listeners?
It seems like this is not clear in pure JavaScript (see Does remove a DOM object (in Javascript) will cause Memory leak if it has event attached?, for example). Looking at Chrome DevTools Timeline, it looks like there are listeners kept around, but I'm not sure if that's related to what I'm asking.
I could, of course, keep around the StreamSubscription
and cancel it "to be sure", but I don't want to do that if it's not absolutely necessary. It makes the code complex.
Upvotes: 1
Views: 238
Reputation: 8128
The garbage collector will remove the listeners (the same way as JS gets rid of unused listeners). You can safely drop the subscriptions if you don't need them anymore.
Upvotes: 3