Avoid memory leak in subscription for baconjs

115 views Asked by At

I have a store in my application that uses the baconjs library. This store listens for changes of my authentication token. As the logged in user changes I then want to update listeners on other events to depend this new token.

However, each time i log in with a new user the old subscribers aren't disposed of. How would I go about solving this problem?

Here is a snippet of code:

token.onValue(token => {
    add.onValue(task => {
        fetch(...);
    });

    update.onValue(task => {
        fetch(...);
    });
});

Note that it is important for me that the fetch always is performed regardless of anyone subscribing to any observable because i want push semantics for these two actions.

1

There are 1 answers

0
OlliM On BEST ANSWER

The problem is that you are combining token with add (and with update) without using combinators. Adding subscribers in a onValue handler is an anti-pattern that should be avoided.

Create a stream which contains both the task and the current token and use that to do the fetching:

Bacon.combineTemplate({
  task: add,
  token: token
}).onValue(function(v) {
  fetch(v.task, v.token);
})