Search code examples
gwtjakarta-eefunctional-programminggwt-rpc

Problem with A Sync callback function in GWT


What I'm doing is:

getSecroleByOrgNID(orgList[i-2],cu.currentUser.getProfileObj());
System.out.println("Value of sec role is "+ secondryRole);

where the getSecroleByOrgNID function is:

private String getSecroleByOrgNID(COrganization srOrg, CProfile srUser) {
    analyticsSrvc.getSecroleByOrgNID(srOrg, srUser,
        new AsyncCallback<String>() {
            @Override
            public void onFailure(Throwable caught) {
            }

            @Override
            public void onSuccess(String result) {
                secondryRole = result;
                System.out.println("Assigned role is " + secondryRole);
            }
        });
    return null;
}

where secondryRole is

String secondryRole = " ";

The output is:

Value of sec role is
Assigned role is Admin

Query is why the "value of sec role is " statement prints before "Assigned role is Admin" since the function is called before print statement of "value of sec role is ". And why does the value of secondryRole remain " " even though its value is reassigned inside the function?


Solution

  • As GWT docs says, in GWT you have to "embrace asynchronous transactions" and forget about synchronous ones.

    The problem is that getSecroleByOrgNID() invoke an asynchronous call to the server but this call doesn't stop execution, so it continues his work (server needs more time to return). You are asking for secondryRole when server doesn't response yet.

    You should call a method always inside onSuccess() that work with server response.