Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run method every 5 seconds related on status

I have method in component that getting data from back end and check statuses

Here is it

 getRecognitionById() {
    this.loaderService.show(null, true);

    this.vendorWebApiService
      .createRecognition(this.executiveChangeId)
      .pipe(take(1))
      .subscribe((res) => {
        this.vendorWebApiService
          .getRecognition(res.taskRequestId, this.executiveChangeId)
          .pipe(take(1))
          .subscribe((recognitionResponse) => {
            if (recognitionResponse.jobStatus === "completed") {
              this.recognitionData = recognitionResponse;
              this.getLatesFeedback();
            }
            if (recognitionResponse.jobStatus === "failed") {
              alert();
            } else {
              
            }
          });
      });
  }

In this part I check status

 this.vendorWebApiService
      .getRecognition(res.taskRequestId, this.executiveChangeId)
      .pipe(take(1))
      .subscribe((recognitionResponse) => {
        if (recognitionResponse.jobStatus === "completed") {
          this.recognitionData = recognitionResponse;
          this.getLatesFeedback();
        }
        if (recognitionResponse.jobStatus === "failed") {
          alert();
        } else {

        }
      });

But problem that if status is another then complete or failed, I need to rerun this logic again every 5 seconds , so every 5 seconds I need to check status and after 10's try, I need to show alert.

How I need to rewrite my code to achieve this logic?

like image 632
Eugene Sukh Avatar asked Mar 02 '23 10:03

Eugene Sukh


1 Answers

You can do this with rxjs

    import { interval, Subject, Subscription } from 'rxjs';
    refresher$: Observable<number>;
    refreshSub: Subscription;
    jobStatus: string = "init"
    checkCount = 0

    checkStatus() {
      this.checkCount++
      this.vendorWebApiService
        .getRecognition(res.taskRequestId, this.executiveChangeId)
        .pipe(take(1))
        .subscribe((recognitionResponse) => {
          jobStatus = recognitionResponse.jobStatus
          this.recognitionData = recognitionResponse
          
        });
    }

    getRecognitionById() {
      this.loaderService.show(null, true);

      this.checkStatus()
   }

    this.refresher$ = interval(5000); // every5 sec
    this.refreshSub = this.refresher$.subscribe(() => {
      this.checkStatus()
      if (this.jobStatus === 'completed') {
        this.getLatesFeedback();
      }
      if (this.jobStatus === 'failed') {
        alert()
      } else {
         if (this.checkCount == 10) {
            alert()
         }
      }

    });

like image 113
Deunz Avatar answered Mar 11 '23 18:03

Deunz