Skip to content

Instantly share code, notes, and snippets.

@morphatic
Created May 4, 2017 01:22
Show Gist options
  • Save morphatic/fe68af82d82b54f0a13db63670b464a2 to your computer and use it in GitHub Desktop.
Save morphatic/fe68af82d82b54f0a13db63670b464a2 to your computer and use it in GitHub Desktop.
Example of polling a REST API every 1.5 seconds with Observables in NodeJS
/**
* Instructions
*
* 1. mkdir test
* 2. cd test
* 3. npm init
* 4. accept all defaults is fine
* 5. npm install @akanass/rx-http-request
* 6. paste code below into new file index.js
* 7. update username, password, other variables
* 8. node index
*/
// import necessary libraries
const Rx = require('rxjs/Rx');
const RxHR = require('@akanass/rx-http-request').RxHR;
// set up api requrest
let uri = 'http://api.timezonedb.com/v2/get-time-zone';
let qs = {
key: 'S3UJYQB3HFMI',
by: 'zone',
zone: 'America/New_York',
format: 'json'
};
// create polling source
let source = Rx.Observable.interval(1500).flatMap(() => RxHR.get(uri, {qs: qs}));
// control variable to let us know when to stop polling
let i = 0;
// start poll
let subscription = source.subscribe(
res => {
console.log(JSON.parse(res.body).formatted);
i++;
if(i > 5) {
subscription.unsubscribe();
}
},
err => {
console.log('error: ', err);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment