How can I develop a method to convert calls to the server API to a Bacon.js / RxJs stream while supporting pagination?
With pagination, I aim to keep track of the last requested item index and retrieve the next set of items based on the page size to populate the stream.
My main requirement is to trigger the 'load next page_size items' function only when all existing items in the stream have been consumed.
Below is a test scenario I created:
var PAGE_SIZE = 20;
var LAST_ITEM = 100;
var FIRST_ITEM = 0;
function fetchItemsFromServer(fromIndex) {
if (fromIndex > LAST_ITEM) {
return [];
}
var remainingItemsCount = LAST_ITEM - fromIndex;
if (remainingItemsCount <= PAGE_SIZE) {
return _.range(fromIndex, fromIndex + remainingItemsCount);
}
return _.range(fromIndex, fromIndex + PAGE_SIZE);
}
function createStream() {
return Bacon.fromBinder(function(sink) {
var fromIndex = FIRST_ITEM;
function loadMoreItems() {
var items = fetchItemsFromServer(fromIndex);
fromIndex = fromIndex + items.length;
return items;
}
var moreItemsAvailable = true;
while (moreItemsAvailable) {
var items = loadMoreItems();
if (items.length < PAGE_SIZE) {
moreItemsAvailable = false;
}
_.forEach(items, function(item) { sink(new Bacon.Next(item)); });
}
return function() { console.log('done'); };
});
}
createStream().onValue(function(value) {
$("#events").append($("<li>").text(value))
});
http://jsfiddle.net/Lc2oua5x/10/
Currently, the 'fetchItemsFromServer' function simply generates items locally. How can I integrate it with an AJAX call or a promise that returns an array of items? The execution should be able to happen multiple times depending on the server's item count and the specified page size.
I looked into using Bacon.fromPromise() as per the documentation but faced difficulties in incorporating it effectively alongside the pagination logic.