简体   繁体   English

如何使用takeUntil取消订阅计时器服务调用

[英]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? 那我应该如何使用takeUntil()方法呢?

I have tried to use this.ngXUnsubscribe in takeUntil() which is not ending the service calls over a period of time. 我试图在takeUntil()中使用this.ngXUnsubscribe,但它不会在一段时间内结束服务调用。 ngXUnsubscribe is defined as follows : ngXUnsubscribe定义如下:

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 我得到的JSON数据是

{
  "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. 因此,在runScenariosDTO数组中,我想添加所有totalExecuted和totalDataset,然后再将它们进行比较。

You should leverage the takeWhile operator ( examples ). 您应该利用takeWhile运算符( 示例 )。

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(...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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