下面的代码是Web服务的for循环,如何在每个循环之前等待boolean为真
检查代码中的评论
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
}
答案 0 :(得分:3)
如何等待直到检查为真然后继续循环
使用递归函数
delare并初始化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);
}
});
}