Search code examples
rokubrightscript

Roku: Is it standard practice to unobserve unused variables after observing them?


Say I was observing a variable

m.someObject.observeField("content", "onContentChanged")

after a certain period of time I no longer need m.someObject. Do I need to cleanup and call

m.someObject.unobserveField("content")

or can I just leave it?


Solution

  • Yes, try to follow this as a good practice, just like when dealing with files after open() should eventually call close() (even as, generally speaking going out of scope takes care of closing connections, it's a good practice to explicitly take care of it).

    Now, beware that node.unobserveField("X") is a "nuclear" option in that it drops any and all observers on node.X that were placed with node.observeField("X", ...), regardless from what component or thread they came. So if having more than one observer per field, you may end up regretting and eventually avoiding unobserveField() use altogether. Mind you, when the node is destroyed, these observers will be taken care of (i.e. not a memory leak).

    Now, there is also a newer API that's better in many cases - the "...Scoped()" versions of these methods. In that version, the node.unobserveFieldScoped("X") is more selective - it only removes the observer(s) on node.X that were placed by the current component; observers set by other components remain active.

    For me it's easier to distinguish between these two approaches by thinking of where is the observer link stored. In the non-scoped versions, all links are stored with the observed object - and so the destructor takes care of cleaning the links. In the scoped versions, links are stored with each observING component - so Unobserve acts locally only on these. And so i believe there is a caveat - if observED object is destroyed, it will leave (temporarily) some hanging scoped links in observING objects. Conversely, if non-scoped ObserveField() was used, destruction of observING object will leave uncleaned link in the observED object (that will get cleaned when it gets droped).