Re: Memory leaks when a ko.computed depends on an external observable

816 views
Skip to first unread message

Roy Jacobs

unread,
Apr 2, 2012, 10:47:56 AM4/2/12
to knock...@googlegroups.com
You can specify a 'disposeWhen' callback with a computed which, when it evaluates to 'true', will dispose the computed.

Here's a small example:

Roy

On Monday, April 2, 2012 11:28:37 AM UTC+2, bcl...@gmail.com wrote:
Hi community,

I attached an example which demonstates the following scenario:
1. I have an observable array
2. Each item placed into this array has a computed observable dependent on a long-living "external" observable (which bevaves like an app-wide option)
3. Due to a specific of my task, I repeatedly add and remove items to / from the array

Problem: items are not disposed automatically, because the external observable is alive. This results in memory leaks: constant growth of ko.subscription objects.
The attached artificial example leaks about 8 MB per second.

NOTE:
I understand that in this specific case I can manually dispose the dependent observable when I remove it from the array. 
But in real-world and less obvious cases it can bcome a huge problem which is very hard to debug.

So do you have any recommendations? 
Should we avoid using observables from long-living scopes inside ko.computed?
Shouldn't you warn users in the documentation?

Roy Jacobs

unread,
Apr 2, 2012, 10:51:43 AM4/2/12
to knock...@googlegroups.com
By the way, here is an update without an observable 'isDisposed':

This would seem identical to my first fiddle, but it actually contains a subtle issue: The 'disposeWhen' is evaluated as soon as any of the dependencies change. So before your 'computed' is re-evaluated it will first check to see if it should be disposed or not. This means that if you dispos your computed but you *never again* change your global observable, the computed still won't be disposed (since it is never re-evaluated and the 'disposeWhen' callback is never called).
Reply all
Reply to author
Forward
Message has been deleted
0 new messages