0

I am just migrating one of my applications to Angular 2 and with it comes RxJS.

I want to refresh my data from server every 5s. At first I figured to do something like this:

Observable.timer(0,5000).flatMap(() => this.http.get(url))

But if the http request takes more than 5 seconds, another one gets sent. I would like it to wait 5s after http request is finished not after it is created.

2 Answers 2

4

You can use the expand Operator to create a new Observable when the source emits an item.

let myRequest = this.http.get(...);
let pollingSubscription = myRequest
 .expand(() => Observable.timer(5000).flatMap(() => myRequest));
 .subscribe();

Docs for expand

Litte bit offtopic but maybe you should look into something like LongPolling

Sign up to request clarification or add additional context in comments.

2 Comments

This sounds perfect, will try it in today. As for websockets, unfortunately we are working with a fixed backend.
LongPolling have nothing to do with Websockets ;)
1

One approach you can adopt is

RequestGet(){
     this.http.get(url)
          .subscribe(e=>{
              // check if response get or not properly
              // if yes call another method
              this.againRequest();
          })
  }
  againRequest(){
    setTimeout(e => {
      this.RequestGet()
    }, 5000)
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.