addObserver method

  1. @useResult
VoidCallback addObserver({
  1. required ObserveReactiveModel listener,
  2. bool shouldAutoClean = false,
  3. bool isSideEffects = true,
})

Add observer to this state.

The observer callback is invoked each time the state is notified.

If shouldAutoClean is true, when the observer is removed and if the state has no other observer, then the state is disposed of.

If isSideEffects is true, then the observer is considered as side effects and is not used to dispose the state.

the return callback must be consumed to remove the observer.

Implementation

@useResult
VoidCallback addObserver({
  required ObserveReactiveModel listener,
  bool shouldAutoClean = false,
  bool isSideEffects = true,
}) {
  if (isSideEffects) {
    _listenersForSideEffects.add(listener);
  } else {
    _listeners.add(listener);
  }
  return () {
    if (isSideEffects) {
      _listenersForSideEffects.remove(listener);
    } else {
      _listeners.remove(listener);
    }

    if (shouldAutoClean && !hasObservers) {
      cleanState();
    }
  };
}