Reputation: 1033
I've recently discovered Bacon.js and have been tinkering but struggling with an issue.
I have an event stream results
for recent GitHub users returned from an AJAX request. Each result event is as an array of user objects, e.g., [{ id: 1, login: 'somlor' }, { id: 2, login: 'raimohanska' }, ...]
QUESTION: I'd like create a new users
event stream that feeds from result events and returns the actual user objects as individual events. Is this possible?
Here is my code for the result stream, this is working as expected:
// get some recent github users
var ajaxStream = function() {
var randomOffset = Math.floor(Math.random() * 500);
var url = 'https://api.github.com/users?since=' + randomOffset;
return Bacon.fromPromise($.ajax(url));
}
// refresh click stream, start as true to trigger initial ajax call
var refresh = $('a.refresh').asEventStream('click')
.map(true)
.startWith(true);
// latest results stream. each event is an array of user objects.
var results = refresh.flatMapLatest(ajaxStream);
This is not working. It creates a single event stream for each results
array. I want it to "split" each results
array into a new event for each user object in that array.
// stream of individual users created from each result event array
var users = results.map(function(e) { return new Bacon.fromArray(e); });
Any ideas?
Thanks,
Sean
UPDATE:
This is what I was looking for:
var users = results.flatMap(Bacon.fromArray);
Upvotes: 2
Views: 753
Reputation: 361
If I understand the question correctly you need to use .flatMap to create the stream.
results.flatMap(Bacon.fromArray).onValue(function(v){ console.log(v) });
Upvotes: 4