Skip to content

Instantly share code, notes, and snippets.

@seanislegend
Last active August 12, 2019 09:43
Show Gist options
  • Save seanislegend/94b3b0bd70b6d9d1af2c to your computer and use it in GitHub Desktop.
Save seanislegend/94b3b0bd70b6d9d1af2c to your computer and use it in GitHub Desktop.
RxJS - Poll a URL
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')
);
@samueljseay
Copy link

Stumbled across this while googling so thanks, very helpful :)

Note that you can use timer(0, timeout) instead of combining take(1) and interval

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment