Last active
October 12, 2018 23:47
-
-
Save ccnokes/010c4fb82d5b8ab935b2e9c1b255a808 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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