watchForFileChanges method

void watchForFileChanges()

Implementation

void watchForFileChanges() {
  logger.detail('Watching ${root.path} for changes');

  if (_watcherSubscription != null) {
    return;
  }

  _watcherSubscription = DirectoryWatcher(root.path).events
      .asyncMap((event) async {
        final WatchEvent(:type, :path) = event;

        if (type == ChangeType.REMOVE) {
          await onFileRemove(path);
        } else {
          await onFilesChange([path]);
        }

        return event;
      })
      .debounce(Duration.zero)
      .listen((event) {
        final WatchEvent(:type, :path) = event;

        _reload(path);
      });

  _watcherSubscription
      ?.asFuture<void>()
      .then((_) async {
        await _cancelWatcherSubscription();
        await stop();
      })
      .catchError((_) async {
        await _cancelWatcherSubscription();
        await stop(1);
      })
      .ignore();
}