Technical Context
I am using jQuery in a web browser to call an API that returns a set of entries from a log.
API requests take two parameters:
offset_timestamp
: an integer specifying the earliest possible entry I wantlimit
: an integer specifying the number of records to return
Example request and response
Request with parameters:
- offset_timestamp = 100
- limit = 50
curl "https://example.com/log?offset_timestamp=100&limit=5"
Resulting JSON Response:
{
next_timestamp: 222,
end_of_log: false,
entries: [
{
timestamp: 111,
data: { ... }
},
{
timestamp: 112,
data: { ... }
},
...
{
timestamp: 160,
data: { ... }
}
]
}
If I were using plain jQuery + callbacks, I think I'd have to chain the AJAX calls recursively. Something along the lines of:
// NOTE: I have NOT tested this code.
// I just wrote it for illustration purposes
function getBatch(offset, limit, callback) {
var url = "https://example.com/logs?offset_timestamp=" + offset + "&limit=" + limit;
var ajaxParams = {
method: "GET",
url: url
};
jQuery.ajax(ajaxParams))
.done(function(data) {
if (data.end_of_log) {
return callback(data.entries);
}
return getBatch(data.next_timestamp, limit, function(entries) {
return callback(entries.concat(data.entires));
});
});
}
function processEntries(entries) {
for (var i = 0; i < entries.length; i++) {
console.log(i.data);
}
}
getBatch(0, 50, processEntries);
Naturally, I would rather have a sequence of Observables (each holding one batch of entries) so I could use flatMap()
to get a sequence of all entries.
Question
If create an Observable from a jQuery call, e.g. Rx.Observable.fromPromise(jQuery.ajax({...}))
, is it possible to use RxJS to chain together an arbitrary number of these Observables, using the value of response.next_timestamp
from the previous call in the parameters of the subsequent call?