Skip to content

Instantly share code, notes, and snippets.

@boris317
Created July 29, 2016 01:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boris317/0a21f326e694d5d893727900c6bbafd0 to your computer and use it in GitHub Desktop.
Save boris317/0a21f326e694d5d893727900c6bbafd0 to your computer and use it in GitHub Desktop.
RXJS Chaining HTTP Calls
var http = require('http');
var RX = require('rx');
var request = require('request');
function get(url) {
return RX.Observable.create(function(observer) {
request(url, function(err, response, body) {
if (err) {
observer.onError(err);
return;
}
observer.onNext(body);
observer.onCompleted();
});
});
}
var source = get('http://httpbin.org/response-headers?count=0');
source
.flatMap(function(body) {
var obj = JSON.parse(body);
return get('http://httpbin.org/response-headers?count=' + (parseInt(obj.count) + 1));
})
.flatMap(function(body) {
var obj = JSON.parse(body);
return get('http://httpbin.org/response-headers?count=' + (parseInt(obj.count) + 1));
})
.subscribe(function(body) { console.log(body) });
@boris317
Copy link
Author

$ node test.js
{
  "Content-Length": "85",
  "Content-Type": "application/json",
  "count": "2"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment