Combining streams which haven't started

29 views
Skip to first unread message

Eyal

unread,
Dec 10, 2014, 12:36:58 PM12/10/14
to bac...@googlegroups.com
Hi,

I am trying to use bacon.js to implement a fairly simple piece of logic. I have an array of objects that I get from an AJAX request, and a value in the list that the user can select in the GUI. I implemented that as two streams, and I would to build a stream which combines both input to identify the item in the list that should be currently selected.

In a non bacon.js world, that would look like

function getSelectedItem(collection, selected) {
if (!_.isUndefined(selected) && _.contains(collection, selected)) {
return selected;
}
return _.first(collection);
}

The problem I have is that the stream which represents the 'selected' stream may or may have a value, and using Bacon.combineXX functions seems to wait for all input streams to have at least one value. So I could resolve that in two ways:

1) Convert the stream which represents the user selected entry to a property which an initial value (for instance undefined). In my toy example, that would be something like:

var b1 = new Bacon.Bus();
var b2 = new Bacon.Bus();
var res = Bacon.combineWith(function(v1, v2) {
return [v1, v2];
}, b1, b2.toProperty(undefined));


2) Use Bacon.when and accept that case where the second stream has not value:

var res = Bacon.when(
[b1, b2.toProperty()], function(v1, v2) {
return [v1, v2];
},
[b1.toProperty(), b2], function(v1, v2) {
return [v1, v2];
},
[b1], function(v1) {
return [v1, undefined];
},
[b2], function(v2) {
return [undefined, v2];
})

I find both implementation not ideal (the first one because it uses undefined to represent a non value, and the second one because of the complexity of converting streams to properties). I've created a jsfiddle which exemplifies the problem:

http://jsfiddle.net/9bys6823/

Two questions for the group:
1) Is the idea of implementing that problem as 2 streams and combining them the right way?
2) Is there an easier (more straightforward) way of implementing that?


Reply all
Reply to author
Forward
0 new messages