logoalt Hacker News

Joerilast Tuesday at 12:56 PM2 repliesview on HN

If listeners of this implementation aren’t unsubscribed they can’t be garbage collected, and in a real world codebase that means memory leaks are inevitable. EventDispatcher has weak refs to its listeners, so it doesn’t have this problem.


Replies

AgentMElast Tuesday at 7:32 PM

The listeners can be garbage-collected if the `greetings` publisher object and any unsubscribe callbacks are garbage-collectable. This is consistent with normal Javascript EventTargets which don't use weak refs.

If only weak refs were kept to listeners, then any listeners you don't plan to unsubscribe and don't keep that callback around will effectively auto-unsubscribe themselves. If this was done and you called `greetings.sub((name) => console.log("hi there", name));` to greet every published value, then published values will stop being greeted whenever a garbage collection happens.

show 1 reply