Last active
August 12, 2019 09:43
-
-
Save seanislegend/94b3b0bd70b6d9d1af2c to your computer and use it in GitHub Desktop.
RxJS - Poll a URL
This file contains 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
let timeout = 1000; | |
/** | |
* Create a custom observable that creates a XHR request and returns complete when the promise is fulfilled | |
*/ | |
let observable = Rx.Observable.create((o) => { | |
dataService.fetch('test.json') | |
.then((data) => { | |
o.onNext(data); | |
o.onCompleted(); | |
}) | |
.fail(o.onError); | |
}); | |
/** | |
* Call our observable immediately and then add an interval for the polled requests | |
*/ | |
let source = observable | |
.take(1) | |
.merge( | |
Rx.Observable | |
.interval(timeout) | |
.flatMapLatest(observable) | |
) | |
/** | |
* Return events from the observable. | |
*/ | |
source.subscribe( | |
(data) => console.log(data), | |
(error) => console.log(error), | |
() => console.log('done') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Stumbled across this while googling so thanks, very helpful :)
Note that you can use
timer(0, timeout)
instead of combiningtake(1)
andinterval