Kumail Hussain
Kumail Hussain

Reputation: 879

Start polling when flag becomes true

I want to start polling when the value of atrribute becomes true, is there any method to start to poll when the flag becomes true, right now my implementation is :

 ngOnInit(){
        //want to start when startedPoll becomes true otherwise dont
        let url = 'getStatus'
        this.pollingSubscribe = interval(5000).pipe(
          switchMap(() => this.http.getCall(url))
        ).subscribe(data => {
          if(data['success']) {
            this.pollingData =data['result']

            this.processData(this.pollingData)
          }

        }, error =>{
          this.error = true;
          this.errorData = this.createPollingFiles;
        })
      }

startPoll(){
  this.startedPoll = true;
}

when startedPoll becomes true start to poll data, please don't suggest the if and else implementation

Upvotes: 0

Views: 158

Answers (1)

Alex Peters
Alex Peters

Reputation: 2916

If the only way startedPoll can become true is when the startPoll method is called, then simply move the subscribe call from your ngOnInit method into startPoll:

ngOnInit() {
    // want to start when startedPoll becomes true otherwise dont
    let url = 'getStatus'
    this.pollingObservable = interval(5000).pipe(
        switchMap(() => this.http.getCall(url))
    );
}

startPoll() {
    this.pollingSubscribe = this.pollingObservable.subscribe(data => {
        if (data['success']) {
            this.pollingData = data['result']
            this.processData(this.pollingData)
        }
    }, error => {
        this.error = true;
        this.errorData = this.createPollingFiles;
    })
    this.startedPoll = true;
}

ngOnDestroy() {
    if (this.pollingSubscribe) {
        this.pollingSubscribe.unsubscribe();
    }
}

Ensure that startPoll is not called more than once while polling is active. Otherwise, the Subscription which is already stored in this.pollingSubscribe will be lost, polling will be doubled in frequency, and some polling will continue after the component is destroyed.

Upvotes: 2

Related Questions