Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active October 12, 2018 23:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccnokes/010c4fb82d5b8ab935b2e9c1b255a808 to your computer and use it in GitHub Desktop.
Save ccnokes/010c4fb82d5b8ab935b2e9c1b255a808 to your computer and use it in GitHub Desktop.
const { Observable } = require('rxjs/Observable');
require('rxjs/add/operator/filter');
require('rxjs/add/operator/switchMap');
require('rxjs/add/operator/take');
require('rxjs/add/operator/toPromise');
const axios = require('axios');
const online$ = createOnline$();
//only make the network request when we're online
//the request will simply get queued up until then
function requestWhenOnline(ajaxPromiseFn) {
return online$
.filter(online => online)
//we only reach this point when we're online
.switchMap(ajaxPromiseFn) //instead of emitting true/false, emit the value of this function
.take(1) //this ensures the observable ends after we've gotten a response
.toPromise(); //convert it all to a promise
}
requestWhenOnline(() => axios.get('http://example.com'))
.then(console.log)
.catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment