0

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?

Farhan Yaseen
  • 2,507
  • 2
  • 22
  • 37

1 Answers1

0

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.

raimohanska
  • 3,265
  • 17
  • 28
  • I did try this, but the subsequence data return empty. I mean using the `scan` but I haven't tried the doAction. Will give it a try. – Not a smart guy Oct 31 '17 at 07:33
  • The doAction works. The scan doesn't (even reset the array after the onValue), this is an interesting behavior of Bacon.js – Not a smart guy Nov 17 '17 at 14:27
  • If you want to discuss why a certain approach (somthing based on scan?) doesn't work even if you think it should, you can post an Issue against the bacon.js github codebase and we'll have a look. Please include runnable code. – raimohanska Nov 18 '17 at 14:57
  • cool thanks, I am actually building a little game with Bacon.js at the moment. So definitely I will have quite a few things want to say :) – Not a smart guy Nov 21 '17 at 15:28