Skip to content

Instantly share code, notes, and snippets.

@pchi
Last active June 27, 2019 15:19
Show Gist options
  • Save pchi/18aa0cc8539fdbcf2a3d to your computer and use it in GitHub Desktop.
Save pchi/18aa0cc8539fdbcf2a3d to your computer and use it in GitHub Desktop.
Short polling until predicate is met with RXJS
function getWikipediaSearchResults(term) {
return Rx.Observable.create(function forEach(observer) {
var cancelled = false;
var url = 'http://en.wikipedia.org/w/api.php?action=opensearch&format=json&search='
+ encodeURIComponent(term) + '&callback=?';
$.getJSON(url, function(data) {
if (!cancelled) {
observer.onNext(data[1]);
observer.onCompleted();
}
});
return function dispose() {
cancelled = true;
};
});
}
// Create an observable that emits a new value every 2 seconds
// substitute interval for Rx.Observable.timer(0, 2000) if you need immediate start
Rx.Observable.interval(2000)
// cancel any pending requests
.flatMapLatest(() => getWikipediaSearchResults('Peter'))
// not necessary but if you need to do something with the response incase its wrapped
.map(response => response)
// give me the first observable that meets our predicate, which then disposes the stream
.first((data) => {
return data.filter(valuesInArray => valuesInArray.indexOf('LIKES') > -1)
})
.subscribe(data => console.log('onNext', data));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment