1

I'm unable to figure out how to return a String value from RequestBuilder's sendRequest() method after receiving a response. I referred to a similar question where the suggestion was to use Callback<String, String> callback but I can't figure out how to implement this. The GWT documentation for Callback does not have any examples.

What I have is a class Requester with the method generateRequest() that should make a request with RequestBuilder and return a String when called. The processResponse() method takes the response, parses it and returns a String which I'm storing in output. How can I return this output String when generateRequest() is called from another class?

public String generateRequest() {
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url.getUrl()));
        builder.setHeader("Authorization", authHeader);
        String title = null;

        try {
            builder.sendRequest(null, new RequestCallback() {

                public void onError(Request request, Throwable exception) {
                    GWT.log(exception.getMessage());
                }

                public void onResponseReceived(Request request, Response response) {
                    String output = processResponse(response);
                }
            });
        } catch (RequestException e) {
            GWT.log(e.getMessage());
        }

    return title;
}
Anish Sana
  • 518
  • 1
  • 12
  • 30

2 Answers2

2

I think you might be misunderstanding something.

You cannot simply return a String because the call is async (i.e. you can't return the String because the String is simply not available yet, at the time you wish to return it). You could simply wait there until the call result is ready, but this is really terrible practice; that's why you're seeing people suggesting callbacks.

Andrei
  • 1,613
  • 3
  • 16
  • 36
1

Imagine, this is the code:

statement01;
statement02;
String result = generateRequest(...);
statement04UsingResult;
statement05;

then this will not work, because result will not be available before statement04UsingResult is executed. The Request has not finished yet. (as Andrej already mentioned)

To solve this, split your code:

statement01;
statement02;
generateRequest(...);

create an new void method, wich accepts the result as parameter:

public void newMethod(String result) {
    statement04UsingResult;
    statement05;
}

and call from inside the onResponseRevieve-method:

           builder.sendRequest(null, new RequestCallback() {

            public void onError(Request request, Throwable exception) {
                GWT.log(exception.getMessage());
            }

            public void onResponseReceived(Request request, Response response) {
                newMethod(processResponse(response));
            }
        });

Hope that helps.

El Hoss
  • 3,767
  • 2
  • 18
  • 24