0

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
        }
    }

1 Answer 1

1

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.