watch<T> static method

ZenWorker watch<T>(
  1. ValueNotifier<T> observable,
  2. void callback(
    1. T
    ), {
  3. WorkerType type = WorkerType.ever,
  4. Duration? duration,
  5. bool condition(
    1. T
    )?,
})

Universal worker creation method with explicit generic type preservation

Implementation

static ZenWorker watch<T>(
  ValueNotifier<T> observable,
  void Function(T) callback, {
  WorkerType type = WorkerType.ever,
  Duration? duration,
  bool Function(T)? condition,
}) {
  // Validate configuration
  if ((type == WorkerType.debounce ||
          type == WorkerType.throttle ||
          type == WorkerType.interval) &&
      duration == null) {
    throw ArgumentError(
        'Duration required for ${type.name}'); // coverage:ignore-line
  }

  // Validate duration is not negative
  if (duration != null && duration.isNegative) {
    throw ArgumentError(
        'Duration cannot be negative'); // coverage:ignore-line
  }

  // Create worker first
  final worker = _ZenWorker<T>(
    type: type,
    callback: callback,
    duration: duration,
    condition: condition,
  );

  // Create a ZenWorker (public API) that delegates to the internal worker
  final zenWorker = ZenWorker(
    () => worker.dispose(),
    pauseFunction: () => worker.pause(),
    resumeFunction: () => worker.resume(),
    isPausedGetter: () => worker.isPaused,
    isDisposedGetter: () => worker.isDisposed,
  );

  // Set worker reference for auto-disposal
  worker.setWorker(zenWorker);

  worker.listenTo(observable);
  return zenWorker;
}