0

I have an array, premisasObtenidas, that I want to update with the contents that I get from a GWT AsyncCallback. The call works fine, and the code of onSuccess executes, but when I try to add what it returns to premisasObtenidas to return it on my getPremisasFromServer method I get a empty list.

How can I return from getPremisasFromServer, the List that I get from the success in the AsyncCallback?

private List<PremisaDTO> getPremisasFromServer() {

        final List<PremisaDTO> premisasObtenidas = new ArrayList<PremisaDTO>();
            //premisasObtenidas is declared on the outside class        

        myService.mostrarPremisas( 

                new AsyncCallback<List<PremisaDTO>>() {

                        public void onFailure(Throwable caught){


                            Window.alert("Falla al cargar premisas" + caught.getMessage());

                        }
                        public void onSuccess(List<PremisaDTO> premisasEnBD){

                            Window.alert("Exito al obtener premisas " + premisasEnBD.get(0).getTextoPremisa());
                            for (int i=0; i<premisasEnBD.size();i++){
                                PremisaDTO aux = new PremisaDTO();
                                aux.setId(premisasEnBD.get(i).getId());
                                aux.setTextoPremisa(premisasEnBD.get(i).getTextoPremisa());
                                premisasObtenidas.add(aux);


                            }
                        }
                } );

        return premisasObtenidas; //here premisasObtenidas has size 0 

    }
andandandand
  • 21,946
  • 60
  • 170
  • 271

1 Answers1

1

This is a subroutine - the async callback doesn't happen inline - i.e. onSuccess hasn't been executed by the time you hit your return statement.

The callback will happen some time in the future (when the server has done it's thing).

What you probably need is

final List<PremisaDTO> premisasObtenidas = new ArrayList<PremisaDTO>();

to be class level (not local to the function). Your onSuccess() populates the list, and then calls some other class method to do something with the list.

This is just the nature of acync programming. Since the server is involved and you don't want the client to become unreactive. You ask the server to do something, and when it is done you (the client) gets told about it (your program is free to continue doing other stuff in the middle).

John3136
  • 28,809
  • 4
  • 51
  • 69