watch<T extends Record> function

WatchHandle watch<T extends Record>(
  1. T compute(),
  2. void runner(
    1. T value,
    2. T? oldValue
    ), {
  3. bool immediate = false,
  4. bool once = false,
})

Watches a computed value and runs a callback when it changes.

The compute function is used to calculate the value to watch. The runner function is called whenever the computed value changes.

Parameters:

  • compute: A function that returns the value to watch.
  • runner: A callback function that is called with the new and old values.
  • immediate: If true, the runner is called immediately on the first run.
  • once: If true, the watch operation stops after the first change.

Returns a WatchHandle that can be used to control the watch operation.

Implementation

WatchHandle watch<T extends Record>(
  T Function() compute,
  void Function(T value, T? oldValue) runner, {
  bool immediate = false,
  bool once = false,
}) {
  int runCounter = 0;
  final scope = createScope();

  scope.run(() {
    T? oldValue;
    final computed = derived<T>(compute);

    effect(() {
      // Track the derived value to trigger the effect.
      final value = computed.value;

      // Skip the first run if immediate is false.
      if (!immediate && runCounter == 0) {
        oldValue = value;
        runCounter++;
        return;
      }

      runner(value, oldValue);

      // If once is true, stop the scope.
      if (once) scope.stop();
      oldValue = value;
      runCounter++;
    });
  });

  return WatchHandle._(scope);
}