{"size": 1073, "ext": "js", "max_stars_repo_path": "src/rx/watch.js", "max_stars_repo_name": "jhamlet/ink", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rx/watch.js", "max_issues_repo_name": "jhamlet/ink", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rx/watch.js", "max_forks_repo_name": "jhamlet/ink", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 23.3260869565, "max_line_length": 64, "alphanum_fraction": 0.5619757689}
import { Observable, of } from 'rxjs';
import { concat, concatMap, delay, take } from 'rxjs/operators';
import { watch as fsWatch } from 'fs';

export const watch = (filepath, opts) =>
  Observable.create(observer => {
    const watcher = fsWatch(filepath, opts);
    let disposed = false;

    const listener = (error, value) =>
      !disposed
        ? error
        ? observer.error(error)
        : observer.next(value)
        : null;

    const change = (type, filename) =>
      listener(null, { type, filename, original: filepath });

    watcher.on('error', listener);
    watcher.on('change', change);

    return () => {
      disposed = true;
      watcher.close();
    };
  });

export const watchFile = (filepath, opts) =>
  watch(filepath, opts).
    pipe(
      take(1),
      concatMap(event =>
        of(event).
          pipe(
            // give tick to allow for file system to update
            // should probably check stats...
            delay(0),
            concat(watchFile(filepath, opts))
          )
      )
    );

export default watch;

