YAObserver<V> constructor

YAObserver<V>(
  1. YAValueGetter<V> getValue, {
  2. required YAObserverChanged<V> onChanged,
  3. YAComparator<V>? hasChanged,
  4. bool updateImmediately = true,
  5. bool fireOnFirstUpdate = false,
  6. int maxHistoryLength = 0,
})

Creates an observer that triggers onChanged whenever the value returned from getValue changes.

If hasChanged is specified and non-null, it will be used by the update method to determine if the value has changed. This is especially useful when comparing objects that can't be properly compared using the == operator, such as List's and other collections. The default behaviour if hasChanged is null is to simply compare the old and new value using ==.

If updateImmediately is true, getValue will be invoked immediately to get the initial value. If false, getValue won't be invoked until you call update.

If fireOnFirstUpdate is true, onChanged will be executed on the first call to getValue. If false, the first call to getValue will not trigger onChanged.

If both updateImmediately and fireOnFirstUpdate are true, getValue will immediately get the initial value and onChanged will be executed with that value. If they are both false, the first call to update will get the initial value, and onChange won't be triggered until the second call to update (if the value has changed since the first call).

maxHistoryLength specifies the number of previous events to include in the history of the event passed to onChanged. It can be used to keep track of which previous changes have happened and at which moments in time.

Implementation

YAObserver(this.getValue,
    {required this.onChanged,
    YAComparator<V>? hasChanged,
    bool updateImmediately = true,
    bool fireOnFirstUpdate = false,
    this.maxHistoryLength = 0})
    : _fireOnFirstUpdate = fireOnFirstUpdate,
      hasChanged =
          hasChanged ?? ((previous, current) => current != previous) {
  if (updateImmediately) {
    _lastEvent = YAObserverEvent<V>(getValue(), DateTime.now());

    if (_fireOnFirstUpdate) {
      onChanged(_lastEvent!);
    }
  }
}