watch<T> static method

ZenWorkerHandle 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 ZenWorkerHandle 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}');
  }

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

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

  // Create handle with proper delegation
  final handle = ZenWorkerHandle(
    () => worker.dispose(),
    pauseFunction: () => worker.pause(),
    resumeFunction: () => worker.resume(),
    isPausedGetter: () => worker.isPaused,
    isDisposedGetter: () => worker.isDisposed,
  );

  // Set handle reference in worker for auto-disposal
  worker.setHandle(handle);

  worker.listenTo(observable);
  return handle;
}