observe()
Creates a reactive observer that runs automatically when tracked observables change. This is the foundation of Legend-State’s reactivity system.Signatures
Parameters
Single callback form
A function that runs immediately and re-runs whenever any observables accessed within it change.The function receives an
ObserveEvent object with:num- The number of times this observer has run (0 for first run)previous- The previous return value from this functioncancel- Set totrueto stop tracking and dispose the observeronCleanup- Set to a function to run cleanup before the next run
Options for the observer:
immediate- Iftrue, ignores batching and runs the callback immediately when observables change (default:false)
Selector/reaction form
A function or observable that computes a value. The reaction will only run when this value changes.Can be:
- A function that returns a value
- An observable
- An observable event
A function that runs when the selector’s value changes (doesn’t run on initial computation).The function receives an
ObserveEventCallback object with:num- The number of times the reaction has runvalue- The current value from the selectorprevious- The previous value from the selectornodes- The observable nodes being trackedrefresh- Function to manually re-run the selectoronCleanup- Set to a function to run cleanup before the next reactiononCleanupReaction- Set to a function to run cleanup when the observer is disposed
Options for the observer (same as single callback form).
Returns
A function that stops observing and cleans up all listeners. Call this when you no longer need the observer.
Examples
Basic observation
Tracking multiple observables
Selector with reaction
Using ObserveEvent
Cleanup with onCleanup
Conditional tracking cancellation
Immediate observation (skip batching)
Observable event with selector
Type Definitions
Notes
observe runs immediately on creation and then again whenever any tracked observables change.