Overview
Theobserve() function is the core mechanism for reacting to changes in observables. It automatically tracks which observables are accessed and re-runs when any of them change.
Basic Usage
Simple Observer
Create a reactive observer that runs when dependencies change:Selector and Reaction
Separate the tracked selector from the reaction:Type Signatures
onChange() Method
Every observable has anonChange() method for listening to its changes:
onChange Parameters
Tracking Options
Shallow Tracking
Only track direct changes, not nested properties:Immediate Execution
Run the listener immediately, bypassing batching:Run on Initial Value
Run the listener once with the current value:Advanced Patterns
Multiple Dependencies
observe() automatically tracks all accessed observables:
Conditional Tracking
Track different observables based on conditions:Cleanup Functions
Use cleanup functions for side effects:Manual Refresh
Manually re-run an observer:Listening to Deep Changes
Nested Object Changes
Array Changes
Disposing Observers
All observe functions return a dispose function:Performance Tips
Use peek() for Non-Dependencies
Shallow Tracking for Performance
Avoid unnecessary re-runs with shallow tracking:Batch Related Changes
Group related changes to trigger only one observer run:Best Practices
Dispose Observers
Always dispose observers when they’re no longer needed to prevent memory leaks.
Use Shallow Tracking
For large objects, shallow tracking can significantly improve performance.
Cleanup Side Effects
Use
onCleanup to properly clean up subscriptions, timers, and other resources.Avoid Infinite Loops
Don’t modify the same observable you’re tracking inside an observer without guards.
Common Pitfalls
Modifying Tracked Observables
Accessing Without get()
Next Steps
Computed Observables
Create derived values that update automatically
Batching
Optimize updates with batching