← Back to context

Comment by Joeri

3 days ago

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.

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.

  • This is correct.

    The subscribers are unlikely to be garbage collected with a weak ref as long as something else is pointing to the subscriber, so it would be a viable alternative to manual unsubscriptions - but personally I prefer to give explicit lifecycle controls to the subscriber, if possible.

    • If the listener is a fresh function passed straight to the listen method as in my example, nothing else will have a reference to it besides the event target, and if that's a weak reference then it will get collected eventually and effectively unsubscribed on its own. Weak references don't make sense at all to use for general event listeners like this.