Ubuntu Learner
Ubuntu Learner

Reputation: 23

How to get variable from GWT Callback

I'm trying to get a state of a server variable using a callback. Obviously, the state is always false. How can I get the state from the server? Or another question, which options do I have to get anything from the server side?

    public static void testCallback(){
        AsyncServiceRegistry.getUserService().isState(new AsyncCallback<Boolean>() {
            @Override
            public void onFailure(Throwable caught) {}
    
            @Override
            public void onSuccess(Boolean result) {
                ApplicationContext.setState(result);
            }
        });

        boolean state = ApplicationContext.getState();
        if (state) {
            System.out.println(true);
            //do smth if true
        } else {
            System.out.println(false);
            //do smth if false
        }
    }

Upvotes: 0

Views: 32

Answers (1)

Colin Alworth
Colin Alworth

Reputation: 18331

Note the Async in AsyncCallback: you're making an async call to your server, but your code is trying to synchronously read the value. Until onSuccess or onFailure is called, no state has yet been returned to the server.

Long ago browsers supported synchronous calls to the server, but GWT-RPC never did, and browsers have since removed that feature except when running on a web worker - the page itself can never do what you are asking.

Two brief options you can pursue (but it would be hard to make a concrete suggestion without more code - i.e. "besides logging the value, what are you going to do with it"):

  • Structure the code that needs this server data such that it can guarantee that the value has already been returned from the server. For example, don't start any work that requires the value until onSuccess has been called (and be sure to handle the onFailure case as well).
  • Guard the server data in some async pattern like a Promise or event, so that the code that needs this value can itself be asynchronous.

Upvotes: 1

Related Questions