PureComputed or Computed with deferEvaluation: Choosing the Right Approach for Automatic Disposal in Complex Dependency Chains
0 reputation · 12 Jul 2021, 22:45 UTC
0 reputation · 12 Jul 2021, 22:45 UTC
Determine the optimal strategy for derived values that participate in deep dependency graphs while ensuring that subscriptions are cleaned up automatically when no longer needed.
deferEvaluation requires explicit disposal and may persist, potentially leaking memory in long‑running applications.When building a view model with multiple layers of derived observables, should developers default to pureComputed for its automatic disposal, or prefer computed with deferEvaluation and manual cleanup to avoid unintended chain termination?
pureComputed automatically dispose intermediate nodes in a nested chain without breaking downstream dependencies?pureComputed is removed from a chain of computed observables?35275 reputation · 13 Jul 2021, 04:56 UTC
In complex dependency chains, you should default to pureComputed for derived values where the lifecycle is tied to the UI or specific consumers. Use computed with deferEvaluation only for values that must persist in memory even when no active subscribers exist, provided you are prepared to manage their manual disposal.
pureComputed is designed for memory efficiency through "active evaluation." In a nested chain (e.g., Observable A → pureComputed B → computed C), the behavior is as follows:
The deferEvaluation flag is a performance optimization that delays the initial calculation until the first subscriber arrives. However, it does not change the lifecycle model:
computed observable remains active indefinitely even if it has zero subscribers. In long-running applications where view models are created dynamically, failing to call dispose() will lead to memory leaks.computed.dispose() during the view model's unmount or cleanup phase.| Feature | pureComputed | computed (deferEvaluation) |
|---|---|---|
| Disposal Strategy | Automatic (at 0 subscribers) | Manual (required) |
| Memory Usage | Lower (suspends when unused) | Higher (persists indefinitely) |
| Use Case | UI-bound derived data | Global state/Background tasks |
pureComputed yields significantly better performance because it avoids the CPU cost of calculating values for branches that are not currently visible or active. Use deferEvaluation only when the value is expensive to compute and you need it to stay ready regardless of the UI state.Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.