WatcherImpl<T> constructor

WatcherImpl<T>(
  1. SourcesFn<T> sourcesFn,
  2. WatcherFn<T> fn, {
  3. bool immediately = false,
  4. WhenFn<T>? when,
  5. JoltDebugFn? onDebug,
})

Creates a new watcher with the given sources and callback.

Parameters:

  • sourcesFn: Function that returns the values to watch
  • fn: Callback function executed when sources change
  • immediately: Whether to execute the callback immediately
  • when: Optional condition function for custom trigger logic

Example:

final signal = Signal(0);

final watcher = Watcher(
  () => signal.value,
  (newValue, oldValue) => print('Changed: $oldValue -> $newValue'),
  immediately: true,
  when: (newValue, oldValue) => newValue > oldValue, // Only when increasing
);

Implementation

WatcherImpl(this.sourcesFn, this.fn,
    {bool immediately = false, this.when, JoltDebugFn? onDebug})
    : super(flags: ReactiveFlags.watching) {
  JoltDebug.create(this, onDebug);

  final prevSub = setActiveSub(this);
  if (prevSub != null) {
    link(this, prevSub, 0);
  }
  try {
    prevSources = sourcesFn();
    if (immediately) {
      untracked(() {
        final prevWatcher = Watcher.activeWatcher;
        Watcher.activeWatcher = this;
        try {
          fn(prevSources, null);
        } finally {
          Watcher.activeWatcher = prevWatcher;
        }
      });
      JoltDebug.effect(this);
    }
  } finally {
    setActiveSub(prevSub);
  }
}