简体   繁体   中英

How to unsubcribe a timer service call using takeUntil

I am calling a service regularly after a certain interval of time. I get two numbers as result in the service response,I want to compare those numbers and if they are equal I want to end the service calls. How am i supposed to use the takeUntil() method then?

I have tried to use this.ngXUnsubscribe in takeUntil() which is not ending the service calls over a period of time. ngXUnsubscribe is defined as follows :

protected ngXUnsubscribe: Subject<void> = new Subject<void>();
 const source = timer(1000,60000);
        source.subscribe(()=> {
        this._helper.runStatus(id)
        .pipe(first(),takeUntil())
        .subscribe(response => {

            let xyz = response && response.runScenariosDTO ? response.runScenariosDTO : []; 
            this.passDataToParent(xyz);
            this.progressBarData = this.ScenariosBasedOnTypeDTO.map(scenario => {

                let pBar = response && response.runScenariosDTO ? response.runScenariosDTO.find(barData => barData.scenarioId ? barData.scenarioId === scenario.scenarioId : undefined) : undefined;
                this.showStatusAfterLoad = 1;

                return this.prepareProgressBarData(scenario, pBar);
             });

            });
         });

I want to stop the execution when those two numbers are equal until then I should keep calling the service.

The JSON data that I am getting it is

{
  "runId": 0,
  "runScenariosDTO": [
    {
      "scenarioId": 0,
      "totalDataset": 0,
      "totalExecuted": 0,
      "totalFailed": 0,
      "totalPassed": 0
    }
  ],
  "totalScenarios": 0
}

So, in the array of runScenariosDTO, I want to add all totalExecuted and totalDataset, and after that I want to comparae them.

You should leverage the takeWhile operator ( examples ).

timer(1000, 60000).pipe(
  switchMap(() => this._helper.runStatus(id)),
  takeWhile(response => {
    const totals = response.runScenariosDTO.map(v => ({ 
       dataset: v.totalDataset, 
       executed: v.totalExecuted 
    }))
    .reduce((sums, v) => ({ 
       dataset: sums.dataset + v.dataset,
       executed: sums.executed + v.executed 
    }), { dataset: 0, executed: 0 });

    return totals.dataset !== totals.executed;
  })
).subscribe(...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM