等待获得布尔值是真的



下面的代码是Web服务上的for循环 如何在每次循环之前等到布尔值为真

检查代码中的注释

    for (i=0;i<contactsString.length-1;i++){
        Phone phone=new Phone();
        phone.phone=contactsString[i];
        check=false;
        WebService.getInstance().getApi().checkNumber(phone).enqueue(new Callback<MainResponse>() {
            @Override
            public void onResponse(Call<MainResponse> call, Response<MainResponse> response) {
                availableUsers++;
                check=true;
            }
            @Override
            public void onFailure(Call<MainResponse> call, Throwable t) {
            }
        });
        //--- here how to wait untill check is true then continue the loop
    }

如何等待直到检查为真,然后继续循环

使用递归函数

availableUsers=0初始化为

字段。要启动循环,请调用checkNumber()

   private int availableUsers=0;
   public void checkNumber() {
      this.checkNumber(0);
   }
   private void checkNumber(final int i){
        if(contactsString==null || i>=contactsString.length){
           return;
        }
        Phone phone=new Phone();
        phone.phone=contactsString[i];
        WebService.getInstance().getApi().checkNumber(phone).enqueue(new Callback<MainResponse>() {
            @Override
            public void onResponse(Call<MainResponse> call, Response<MainResponse> response) {

                availableUsers++;                    
                checkNumber(i+1);
            }
            @Override
            public void onFailure(Call<MainResponse> call, Throwable t) {  
               checkNumber(i+1);
            }
        });
}

最新更新