watch method

Stream<SyncResult> watch({
  1. Duration interval = const Duration(milliseconds: 250),
})

Polls for changes committed by other processes or handles and emits every SyncAppended / SyncCompacted (never SyncUpToDate).

Each tick is a cheap sync (a lock-file generation check plus one length query when nothing changed). Ticks never overlap, the stream pauses polling while paused, and it closes when this handle is closed. Sync failures are delivered as stream errors.

final sub = pack.watch().listen((change) => reloadUi(change));

Implementation

Stream<SyncResult> watch({
  Duration interval = const Duration(milliseconds: 250),
}) {
  if (interval <= Duration.zero) {
    throw ArgumentError.value(interval, 'interval', 'Must be positive');
  }
  _ensureOpen();
  Timer? timer;
  var busy = false;
  late final StreamController<SyncResult> controller;

  Future<void> tick() async {
    if (controller.isClosed) {
      timer?.cancel();
      return;
    }
    if (busy) {
      return;
    }
    busy = true;
    try {
      final result = await sync();
      if (result is! SyncUpToDate && !controller.isClosed) {
        controller.add(result);
      }
    } on WalPackClosedException {
      timer?.cancel();
      await controller.close();
    } on Object catch (error, stack) {
      if (!controller.isClosed) {
        controller.addError(error, stack);
      }
    } finally {
      busy = false;
    }
  }

  void start() => timer = Timer.periodic(interval, (_) => tick());
  void stop() => timer?.cancel();

  controller = StreamController<SyncResult>(
    onListen: start,
    onPause: stop,
    onResume: start,
    onCancel: () {
      stop();
      _watchers.remove(controller);
    },
  );
  _watchers[controller] = stop;
  return controller.stream;
}