Node and RxJs: How can I avoid a memory leak on a long process?
<h3>I'm programming a process that will take a long time running and I'm looking to optimize used memory</h3>

<p>I have an stream of data that comes over time and I want a way to clean up this data and declared variables when the stream completes. Any ideas?</p>

<p>I have setted up a quick example of the problem:</p>

<pre><code>var source = Rx.Observable.interval(100)
                         .take(20)
                         .map((x) =&gt; {
                             let onlyTrash = _.range(1000000);
                             return x;
                         });

let subscription = source.subscribe(
    x =&gt; console.log(getMemoryUsage()),
    err =&gt; console.log('Error: ' + err),
    () =&gt; console.log('Completed: ' + getMemoryUsage())
);
</code></pre>

<p>I can not show this in a Fiddle because it's referencing to process to get memory usage</p>

<p>If you run this example you will notice that memory usage is increasing in each tick but It doesn't decrease on completion, <strong>this is the problem</strong>.</p>

<p>Here is a example of the getMemoryUsage function if you want to try it in your node</p>

<pre><code>var lastMemoryUsageRegister;
function getMemoryUsage() : string {
    var memoryUsage : string;
    if (!lastMemoryUsageRegister) {
        memoryUsage = process.memoryUsage().rss.toString();
    } else {
        let diff = process.memoryUsage().rss - lastMemoryUsageRegister;
        memoryUsage = (diff &gt; 0 ? '+' : '') + diff;
    }
    lastMemoryUsageRegister = process.memoryUsage().rss;
    return memoryUsage;
}
</code></pre>