【问题标题】:Bacon Bus weird behaviour with end of stream event流事件结束的培根总线奇怪行为
【发布时间】:2014-06-02 06:37:15
【问题描述】:

这很好用:

var Bacon = require('baconjs');

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

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

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

... 表示 onValue 和 onEnd 被正确调用,结果如下:

1
2
3
END

这不像(至少我)预期的那样工作:

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)

...这意味着在这种情况下,'onEnd' 没有被调用,结果只是:

1
2
3

有什么原因吗?解决办法是什么?

更新

这正是我最终需要的:

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)

基本上,我需要知道公共汽车何时结束,以便我可以向数据库请求另一块记录,等等。 问题是总线上没有“结束”信号就无法工作。虽然这样的事情有效:

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);

那里有一个回调,这让我很恼火。所以上面的实际解决方案是相当不错的

【问题讨论】:

    标签: javascript reactive-programming frp bacon.js


    【解决方案1】:

    那是因为总线没有结束:您仍然可以将更多事件推送到总线。 Bus 结束的唯一情况是您在 Bus 上调用 end() 方法。

    【讨论】:

    • 在第一种情况下我可以使用 .fold(...) 但在第二种情况下我不能。我需要做什么才能使用 .fold ?
    • 顺便说一句,我意识到这行得通:gist.github.com/haknick/11010798 但是我会有一个回调
    • 您不能折叠无限的列表或无尽的流。您可以改用scan,或者您可以使用 bus.end() 将 End 事件推送到您的总线。
    • 我用最终解决方案更新了答案。在这种情况下,“combineTemplate”会产生奇迹,因为它仅用于通知“ff”流结束,这反过来又允许我重新推入总线,直到我所有的记录块都完成为止。实际上很整洁
    猜你喜欢
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    • 2014-07-09
    • 1970-01-01
    相关资源
    最近更新 更多