user411103
user411103

Reputation:

Turn GWT Asyncronous call (DispatchAsync) into Syncronous

Function canReveal() returns true if class ClientState has user information. If not, it first tries to get that user information using asyncronous call to GetUser. What I need to do inside the IF is to wait somehow until this asyncronous call returns (onSuccess), so that I can check whether ClientState has now the user information or not. How can I do that? Thanks

public class MyGatekeeper implements Gatekeeper{

private DispatchAsync dispatcher;

@Inject
public MyGatekeeper(DispatchAsync dispatcher) {
        this.dispatcher = dispatcher;
}

@Override
public boolean canReveal() {
    if(ClientState.isUserLoggedin()==false) {
        dispatcher.execute(new GetUser(Window.Location.getHref()),
        new DispatchCallback<GetUserResult>() {
                @Override
                        public void onSuccess(GetUserResult result) {
                if (!result.getErrorText().isEmpty()) {
                     Window.alert(result.getErrorText());
                     return;
                }
                ClientState.setUserInfo(result.getUserInfo());
            }
        });
        return ClientState.isUserLoggedin(); // WAIT till onSuccess returns!
    }
}
    return ClientState.isUserLoggedin();
}

Upvotes: 0

Views: 379

Answers (1)

Jason Hall
Jason Hall

Reputation: 20930

The way to do this is to have canReveal take a Callback<Boolean>:

public void canReveal(Callback<Boolean> cb) {
  if (!ClientState.isUserLoggedIn()) {
    dispatcher.execute(..., new DispatchCallback<Result>() {
      @Override
      public void onSuccess(Result result) {
        cb.onSuccess(result.isGoodOrWhatever());
      }
    });
  } else {
    cb.onSuccess(true); // User is logged in
  }
}

Unfortunately there's no way to tell GWT to "wait" for the async callback, since that would basically freeze JS execution, since JS is single-threaded.

Upvotes: 1

Related Questions