Stream stays cold, despite having listener, when passed through function
disantlor opened this issue · comments
I've arrived at a pattern (simplified below) for organizing my bacon code. I'm certainly open to suggestions for improvement, but it seems to reveal a bug, either in bacon or in my understanding of cold streams. The idea was for the user of the class to not have to know about / interact directly with the Bus. The only way I can get the result back out to the .log() is to put a no-op .onValue within SomeClass.js after _updateResult.
--------index.js------------
var someClass = new SomeClass();
someClass.updateData({ a: 1, b: 2}).log('update result:');
-------- SomeClass.js-------
module.exports = function(){
var _updateBus = new Bacon.Bus();
var _updateResult = _updateBus.flatMap(request => Bacon.fromPromise(... some server call))
return {
updateData: function(request){
_updateBus.push(request);
return _updateResult;
}
}
}
This happens when the stream created in flatMap
fires syncnronously and your updateData
function pushes to the bus before your log
subscriber has been added to the stream. You can fix this either by
- delaying the
push
usingsetTimeout
or similar method (now your subscriber is there when the event is fired) or - adding a nop subscriber using
_updateResult.onValue()
. This has the side-effect that the stream will always be active, but this is not likely a problem, because the stream is based on a Bus, so it won't cause resource leaks
Ahhh that makes sense. I ended using the second idea already but good to know that it most likely wouldn't be a problem.
Would it also then work to add .toProperty like:
var _updateResult = _updateBus.toProperty().flatMap.....
Btw thanks and thank you for bacon.js, I'm a total convert and evangelist; it makes programming so much more enjoyable than the pre-bacon era (PBE)