简体   繁体   English

避免baconjs订阅中的内存泄漏

[英]Avoid memory leak in subscription for baconjs

I have a store in my application that uses the baconjs library. 我的应用程序中有一个使用baconjs库的商店。 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. 请注意,对我来说很重要的一点是,无论任何订阅任何可观察项的人都总是执行获取操作,因为我要为这两个动作提供推语义。

The problem is that you are combining token with add (and with update ) without using combinators. 问题是您在不使用组合器的情况下将tokenadd (和update )组合在一起。 Adding subscribers in a onValue handler is an anti-pattern that should be avoided. onValue处理程序中添加订阅服务器是应避免的反模式。

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);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM