0

This works fine:

var Bacon = require('baconjs');

var a = Bacon.fromArray([1,2,3])

a.onValue(function(val){
  console.log(val)
})

a.onEnd(function(){
  console.log("END")
})

... meaning that onValue and onEnd got called properly and this is the result:

1
2
3
END

This doesn't work as (at least I) expected:

var Bacon = require('baconjs');

var bus = new Bacon.Bus();

var a = bus.flatMap(function(){
  return Bacon.fromArray([1,2,3])
})

a.onValue(function(val){
  console.log(val)
})

a.onEnd(function(){
  console.log("END")
})

bus.push(1)

... meaning that in this case 'onEnd' didn't get called, with the result just being:

1
2
3

Is there a reason and what would be the solution ?

UPDATE

Here's exactly what I needed in the end:

var Bacon = require('baconjs');

var a = Bacon.fromArray([1,2,3])
            .fold(0,function(a,b){return a+b;})
            .filter(function(val){ return val > 0 });


var bus = new Bacon.Bus();


var ff = bus.flatMap(function(){
  return Bacon.combineTemplate({status:true, result:a});

});

ff.onValue(function(val){
  console.log(val)
    setImmediate(function(){
    bus.push(3)  
  })

})

ff.onEnd(function(){
  console.log("END")

})


bus.push(3)

Basically I needed to know when the bus ended so that I could ask the database for another chunk of records, and so on. The problem is that without an 'end' signal on the bus that wouldn't work. And although something like this works:

var Bacon = require('baconjs');

var bus = new Bacon.Bus();

bus.onValue(function(){

  var a = Bacon.fromArray([1,2,3])

  a.onValue(function(val){
    console.log(val)
  })

  a.onEnd(function(){
    console.log("END")
  })

})

bus.push(1);

The fact that there is a callback there was annoying me to no end. So the actual solution above is quite nice

haknick
  • 1,862
  • 1
  • 20
  • 28

1 Answers1

1

That would be because the Bus doesn't end: you can still push more events to the Bus. The only case when a Bus ends is when you call the end() method on the Bus.

raimohanska
  • 2,856
  • 11
  • 22
  • On the first case I can use .fold(...) but on the second I can't. What would I have to do to be able to use .fold ? – haknick Apr 17 '14 at 20:42
  • And btw I realize this works: https://gist.github.com/haknick/11010798 but then I would have a callback – haknick Apr 17 '14 at 20:51
  • 1
    You can't fold over infinite lists or endless streams. You can use `scan` instead, or you can push an End event to your Bus using bus.end(). – raimohanska Apr 18 '14 at 20:48
  • I updated the answer with the final solution. 'combineTemplate' in this case works wonders since it's only used to notify 'ff' that the stream ended, which in turn allows me to re-push into the bus, until all my chunks of records are done. Quite neat actually – haknick Apr 20 '14 at 07:38