Baconjs return only last debounce value

129 Views Asked by At

Here is the code sample:

let watcher;
const streamWatcher = bacon.fromBinder(sink => {
    watcher = chokidar.watch(root, {
        ignored: /(^|[\/\\])\../
    });
    watcher.on('all', (event, path) => {
        sink({
            event: event,
            path: path
        });
        return () => {
            watcher.unwatch(root);
        };
    });
});
streamWatcher
    .skipDuplicates(_.isEqual)
    .map('.path')
    .scan([], (a, b) => {
        a.push(b);
        return a;
    })
    .debounce(300)
    .onValue(files => {
        if (files.length) {
            console.log('change event fired');
            tinyLrSrv.changed({
                body: {
                    files: files
                }
            });
        }
    });

What I am trying to do is to use chokidar watch a folder change (a web dir under development) then using Bacon.js to wrap and debounce (because I don't want to know each file change, just tell me in a batch) and return the array of files that changed.

The problem is - the array is from the beginning, so everytime file change, it just keeps adding to the original array.

What I want to get is the last changed array of files, in another word, every time the onValue receives the array, the variable that holds the array needs to reset.

Is there a pure bacon.js way to do this?

1

There are 1 best solutions below

4
raimohanska On

Can't think of a super "pure" way to do this nicely. Did you notice that you're actually mutating your buffer in scan? You could exploit this and actually clear the buffer in your onValue code. Just remember to clone the buffer when sending to tinyLrSrv. Another way would be to use a variable:

var files = []
streamWatcher.skipDuplicates(_.isEqual).map('.path')
  .doAction(a => files.push(a))
  .debounce(300)
  .onValue(() => {
    if (files.length) {
      timyLrSrv.changed({body: {files}})
      files = []
    }
  })

I've had a similar problem myself and haven't figured out a nice "pure" way to do this. Please submit an Issue against Bacon.js and we can figure out if there's something we should add to Bacon.js core.