Replies: 1 comment 4 replies
-
I think it can be done like this: function disposableKeepAliveComputed(expr) {
const disposed = observable.box(false);
const c = computed(() => {
if (!disposed.get()) {
return expr()
}
}, { keepAlive: true })
return {
get() {
return c.get();
},
dispose() {
disposed.set(true); // invalidate computed
c.get(); // make sure it recalculates even without observers
}
}
} The idea is to make sure it doesn't observe anything that could linger around longer than the computed itself and also the cache doesn't hold onto any ref. |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I was wondering if it's somehow possible to get the benefits of lazy execution of mobx computed with
keepAlive
while also being able to dispose of the computed when it's no longer needed.Here's an example:
c2
won't calculate because it's never read butc1
will recalculate on every write (it's "eagerly" observed bykeepAlive
).This would be quite useful when there's an expensive calculation and I want to avoid recalculating it until the value is actually read. But I also don't want to use
keepAlive: true
because of memory leaks.The closest I can get to this is:
But that uses internal mobx API.
Beta Was this translation helpful? Give feedback.
All reactions