Created
March 2, 2016 05:56
-
-
Save whiteinge/90ba12057c3a54d578cb to your computer and use it in GitHub Desktop.
Render a spinner while waiting for an ajax response using RxJS
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
// Central xhr progress tracker. Used for both a global | |
// activity indicator as well as granular spinners within in a page. | |
var Progress$ = new Rx.Subject(); | |
// Make an xhr call and make a tag to track the progress ticks. | |
var users$ = Rx.DOM.ajax({ | |
method: 'GET', | |
url: 'https://api.github.com/users', | |
responseType: 'json', | |
progressObserver: Rx.Observer.create( | |
ev => Progress$.onNext({ | |
tag: 'users', | |
data: {xhr: ev.target, ev: ev}, | |
}) | |
), | |
}); | |
// Filter just the ticks we care about for this particular spinner. | |
var usersProgress$ = Progress$ | |
.filter(x => x.tag === 'users') | |
.pluck('data'); | |
// Trigger a render whenever something of interest comes through. | |
var view$ = users$ | |
.delay(2000) // artificial delay to accentuate the spinner. | |
.pluck('response') | |
.startWith(false) | |
.combineLatest(usersProgress$, function(users, progress) { | |
if (users && progress.ev.type === 'load') { | |
return users.map(user => '<p>' + user.login + '</p>').join('\n'); | |
} else { | |
return '<p>Loading...</p>'; | |
} | |
}); | |
// Output each progress tick. Replace with React.render() or | |
// other rendering layer du jour. | |
var sub1 = view$.subscribe(function(content) { | |
document.querySelector('#content').innerHTML = content; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment