Last active
June 27, 2019 15:19
-
-
Save pchi/18aa0cc8539fdbcf2a3d to your computer and use it in GitHub Desktop.
Short polling until predicate is met with 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
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