Pregunta

This question is very useful. There're some questions about calling multiple AsyncCallback but they didn't tell how to call them in a loop.

Here is my problem. I am doing a project using Gwt-platform. I got a presenter TestPresenter.java which has these codes:

@Inject
DispatchAsync dispatchAsync;

private AsyncCallback<GetDataResult> getDataCallback = new AsyncCallback<GetDataResult>() {

    @Override
    public void onFailure(Throwable caught) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onSuccess(GetDataResult result) {
       // do Something o show the gui here
    }
};

public void load_All_Gui_At_Once() {
    for(int i=0; i<5; i++) {
        GetData getDataAction=new GetData(i);
        dispatchAsync.execute(getDataAction, getDataCallback);
    }
}

The problem is that the program show the data but it showed in the wrong order. This is cos the next Async method started to run while the previous one has not finish yet.

Some suggested me to put the 2nd call inside onSuccess, but that is only for simple 2 sync calls. But in my case, I have to loop many unknown number of Async calls, then how can i do it?

¿Fue útil?

Solución

This is a question similar to this one. All your calls are executed in the same instant, but the response time is unknown and it is not guaranteed the order. So the solution is almost the same, call the loop inside the callback. Your code should look like:

@Inject
DispatchAsync dispatchAsync;

private AsyncCallback<GetDataResult> getDataCallback = new AsyncCallback<GetDataResult>() {
  int idx = 0;

  @Override
  public void onFailure(Throwable caught) {
    // TODO Auto-generated method stub
  }

  @Override
  public void onSuccess(GetDataResult result) {
    if (result != null) {
      // do Something or show the gui here
    }
    if (idx < 5) {
      GetData getDataAction = new GetData(idx);
      dispatchAsync.execute(getDataAction, getDataCallback);
    }
    idx ++;
  }
};

public void load_All_Gui_At_Once(){
  // Start the loop, calling onSuccess the first time
  getDataCallback.onSuccess(null);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top