Skip to content

Instantly share code, notes, and snippets.

@seanislegend
Last active May 10, 2025 03:56
Show Gist options
  • Select an option

  • Save seanislegend/94b3b0bd70b6d9d1af2c to your computer and use it in GitHub Desktop.

Select an option

Save seanislegend/94b3b0bd70b6d9d1af2c to your computer and use it in GitHub Desktop.
RxJS - Poll a URL
/**
* Create a custom observable that creates a XHR request and returns complete when the promise is fulfilled
*/
let dataObservable = Rx.Observable.create((o) => {
dataService.fetch('test.json')
.then((data) => {
o.onNext(data);
o.onCompleted();
})
.fail(o.onError);
});
/**
* Use our observable and call every 2 seconds.
*/
let source = Rx.Observable
.interval(this.options.timeout)
.flatMapLatest(() => this.observer);
/**
* 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