require(["esri/core/reactiveUtils"], (reactiveUtils) => { /* code goes here */ });
import * as reactiveUtils from "@arcgis/core/core/reactiveUtils.js";
esri/core/reactiveUtils
- Overview
- Using reactiveUtils
- Working with collections
- Working with objects
- WatchHandles and Promises
- Working with truthy values
Overview
reactiveUtils
provide capabilities for observing changes to the state of the API's properties,
and is an important part of managing your application's life-cycle.
State can be observed on a variety of different data types and structures
including strings, numbers, arrays, booleans, collections, and objects.
Using reactiveUtils
reactiveUtils
provides five methods that offer different patterns and capabilities for observing state:
on(), once(), watch(), when() and whenOnce().
The following is a basic example using reactiveUtils.watch(). It demonstrates how to track the
MapView.updating property and then send a message to the console
when the property changes. This snippet uses a getValue
function as an expression that evaluates the
updating
property, and when a change is observed the new value is passed to the callback:
// Basic example of watching for changes on a boolean property
reactiveUtils.watch(
// getValue function
() => view.updating,
// callback
(updating) => {
console.log(updating)
});
Working with collections
reactiveUtils
can be used to observe for changes within a collection, such as Map.allLayers. Out-of-the-box JavaScript methods
such as .map()
and .filter()
can be used as
expressions to be evaluated in the getValue
function.
// Watching for changes within a collection
// whenever a new layer is added to the map
reactiveUtils.watch(
() => view.map.allLayers.map( layer => layer.id),
(ids) => {
console.log(`FeatureLayer IDs ${ids}`);
});
Working with objects
With reactiveUtils
you can track named object properties through dot notation (e.g. view.updating
) or
through bracket notation (e.g. view["updating"]
). You can also use the
optional chaining operator (?.
). This operator
simplifies the process of verifying that properties used in the getValue
function
are not undefined
or null
.
// Watch for changes in an object using optional chaining
// whenever the map's extent changes
reactiveUtils.watch(
() => view?.extent?.xmin,
(xmin) => {
console.log(`Extent change xmin = ${xmin}`)
});
WatchHandles and Promises
The watch(), on() and when() methods return a WatchHandle which can be used to remove the watcher when it is no longer needed,.
// Use a WatchHandle to stop watching
const handle = reactiveUtils.watch(
() => view?.extent?.xmin,
(xmin) => {
console.log(`Extent change xmin = ${xmin}`)
});
// In another function
handle.remove()
The once() and whenOnce() methods return a Promise instead of a WatchHandle
.
In some advanced use cases where an API action may take additional time, these
methods also offer the option to cancel the async callback via an
AbortSignal
.
// Use an AbortSignal to cancel an async callback
// during view animation
const abortController = new AbortController();
// Observe the View's animation state
reactiveUtils.whenOnce(
() => view?.animation, abortController.signal)
.then((animation) => {
console.log(`View animation state is ${animation.state}`)
});
// Cancel the async callback
const someFunction = () => {
abortController.abort();
}
Working with truthy values
The when() and whenOnce() methods watch for truthy values, these are values that evaluate to true
in boolean contexts. To learn more about using truthy, visit this
MDN Web doc article. The snippets below use the Popup.visible property, which is a boolean.
// Observe for changes on a boolean property
reactiveUtils.when(() => view.popup?.visible, () => console.log("Truthy"));
reactiveUtils.when(() => !view.popup?.visible, () => console.log("Not truthy"));
reactiveUtils.when(() => view.popup?.visible === true, () => console.log("True"));
reactiveUtils.when(() => view.popup?.visible !== undefined, () => console.log("Defined"));
reactiveUtils.when(() => view.popup?.visible === undefined, () => console.log("Undefined"));
- See also
Method Overview
Name | Return Type | Summary | Object |
---|---|---|---|
Watches the value returned by the | reactiveUtils | ||
Promise | Tracks any properties being evaluated by the | reactiveUtils | |
Tracks any properties accessed in the | reactiveUtils | ||
Watches the value returned by the | reactiveUtils | ||
Promise | Tracks any properties being evaluated by the | reactiveUtils |
Method Details
-
on
on(getTarget, eventName, callback, options){WatchHandle}
-
Watches the value returned by the
getTarget
function for changes and automatically adds or removes an event listener for a given event, as needed.ParametersgetTarget ReactiveOnExpressionFunction which returns the object to which the event listener is to be added.
eventName StringThe name of the event to add a listener for.
callback ReactiveOnCallbackThe event handler callback function.
options ReactiveListenerOptionsoptionalOptions used to configure how the tracking happens and how the callback is to be called.
ReturnsType Description WatchHandle A watch handle. Examples// Adds a click event on the view when it changes reactiveUtils.on( () => view, "click", (event) => { console.log("Click event emitted: ", event); });
// Adds a drag event on the view and adds a callback // to check when the listener is added and removed. // Providing `once: true` in the ReactiveListenerOptions // removes the event after first callback. reactiveUtils.on( () => view, "drag", (event) => { console.log(`Drag event emitted: ${event}`); }, { once: true, onListenerAdd: () => console.log("Drag listener added!"), onListenerRemove: () => console.log("Drag listener removed!") });
-
Tracks any properties being evaluated by the
getValue
function. WhengetValue
changes, it returns a promise containing the value. This method only tracks a single change.ParametersgetValue ReactiveWatchExpressionExpression to be tracked.
signal AbortSignaloptionalAbort signal which can be used to cancel the promise from resolving.
ReturnsType Description Promise A promise which resolves when the tracked expression changes. Examples// Observe for the first time a property equals a specific string value // Equivalent to watchUtils.once() reactiveUtils.once( () => featureLayer.loadStatus === "loaded") .then(() => { console.log("featureLayer loadStatus is loaded."); });
// Use a comparison operator to observe for a first time // difference in numerical values const someFunction = async () => { await reactiveUtils.once(() => view.zoom > 20)); console.log("Zoom level is greater than 20!"); }
// Use a comparison operator and optional chaining to observe for a // first time difference in numerical values. reactiveUtils.once( () => map?.allLayers?.length > 2) .then((value) => { console.log(`The map now has ${value} layers.`); });
-
watch
watch(getValue, callback, options){WatchHandle}
-
Tracks any properties accessed in the
getValue
function and calls the callback when any of them change.ParametersgetValue ReactiveWatchExpressionFunction used to get the current value. All accessed properties will be tracked.
callback ReactiveWatchCallbackThe function to call when there are changes.
options ReactiveWatchOptionsoptionalOptions used to configure how the tracking happens and how the callback is to be called.
ReturnsType Description WatchHandle A watch handle. Examples// Watching for changes in a boolean value // Equivalent to watchUtils.watch() reactiveUtils.watch( () => view.popup.visible, () => { console.log(`Popup visible: ${visible}`); });
// Watching for changes within a Collection reactiveUtils.watch( () => view.map.allLayers.length, () => { console.log(`Layer collection length changed: ${view.map.allLayers.length}`); });
// Watch for changes in a numerical value. // Providing `initial: true` in ReactiveWatchOptions // checks immediately after initialization // Equivalent to watchUtils.init() reactiveUtils.watch( () => view.zoom, () => { console.log(`zoom changed to ${view.zoom}`); }, { initial: true });
// Watch properties from multiple sources const handle = reactiveUtils.watch( () => [view.stationary, view.zoom], ([stationary, zoom]) => { // Only print the new zoom value when the view is stationary if(stationary){ console.log(`Change in zoom level: ${zoom}`); } } );
-
when
when(getValue, callback, options){WatchHandle}
-
Watches the value returned by the
getValue
function and calls the callback when it becomes truthy.ParametersgetValue ReactiveWatchExpressionFunction used to get the current value. All accessed properties will be tracked.
callback ReactiveWatchCallbackThe function to call when the value becomes truthy.
options ReactiveWatchOptionsoptionalOptions used to configure how the tracking happens and how the callback is to be called.
ReturnsType Description WatchHandle A watch handle. Examples// Observe for when a boolean property becomes not truthy // Equivalent to watchUtils.whenFalse() reactiveUtils.when( () => !layerView.updating, () => { console.log("LayerView finished updating."); });
// Observe for when a boolean property becomes true // Equivalent to watchUtils.whenTrue() reactiveUtils.when( () => view?.stationary === true, async () => { console.log("User is no longer interacting with the map"); await drawBuffer(); });
// Observe a boolean property for truthiness. // Providing `once: true` in ReactiveWatchOptions // only fires the callback once // Equivalent to watchUtils.whenFalseOnce() reactiveUtils.when( () => !widget.visible, () => { console.log(`The widget visibility is ${widget.visible}`); }, { once: true });
-
Tracks any properties being evaluated by the
getValue
function. WhengetValue
becomes truthy, it returns a promise containing the value. This method only tracks a single change.ParametersgetValue ReactiveWatchExpressionExpression to be tracked.
signal AbortSignaloptionalAbort signal which can be used to cancel the promise from resolving.
ReturnsType Description Promise A promise which resolves once the tracked expression becomes truthy. Examples// Check for the first time a property becomes truthy // Equivalent to watchUtils.whenOnce() reactiveUtils.whenOnce( () => view.popup?.visible) .then(() => { console.log("Popup used for the first time"); });
// Check for the first time a property becomes not truthy // Equivalent to watchUtils.whenFalseOnce() const someFunction = async () => { await reactiveUtils.whenOnce(() => !layerview.updating); console.log("LayerView is no longer updating"); }
// Check for the fist time a property becomes truthy // And, use AbortController to potentially cancel the async callback const abortController = new AbortController(); // Observe the View's animation state reactiveUtils.whenOnce( () => view?.animation, abortController.signal) .then((animation) => { console.log(`View animation state is ${animation.state}`) }); // Cancel the async callback const someFunction = () => { abortController.abort(); }
Type Definitions
-
ReactiveEqualityFunction
ReactiveEqualityFunction(newValue, oldValue){Boolean}
-
Function used to check whether two values are the same, in which case the watch callback isn't called.
ParametersnewValue *The new value.
oldValue *The old value.
ReturnsType Description Boolean Whether the new value is equal to the old value.
-
Callback to be called when a event listener is added or removed.
Parametertarget *optionalThe event target to which the listener was added or from which it was removed.
-
ReactiveListenerOptions
ReactiveListenerOptions Object
-
Options used to configure the behavior of reactiveUtils.
- Properties
-
sync BooleanDefault Value:false
Whether to fire the callback synchronously or on the next tick.
once BooleanDefault Value:falseWhether to fire the callback only once.
onListenerAdd ReactiveListenerChangeCallbackCalled when the event listener is added.
onListenerRemove ReactiveListenerChangeCallbackCalled when the event listener is removed.
-
Function called to be called when an event is emitted or dispatched.
Parameterevent *The event emitted by the target.
-
Function which is auto-tracked and should return an event target to which an event listener is to be added.
ReturnsType Description * The event target.
-
Function to be called when a value changes.
ParametersnewValue *The new value.
oldValue *The old value.
-
Function which is auto-tracked and should return a value to pass to the ReactiveWatchCallback
ReturnsType Description * The new value.
-
ReactiveWatchOptions
ReactiveWatchOptions Object
-
Options used to configure how auto-tracking is performed and how the callback should be called.
- Properties
-
initial BooleanDefault Value:false
Whether to fire the callback immediately after initialization, if the necessary conditions are met.
sync BooleanDefault Value:falseWhether to fire the callback synchronously or on the next tick.
once BooleanDefault Value:falseWhether to fire the callback only once.
equals ReactiveEqualityFunctionFunction used to check whether two values are the same, in which case the callback isn't called. Checks whether two objects, arrays or primitive values are shallow equal, e.g. one level deep. Non-plain objects are considered equal if they are strictly equal (===).