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;
}
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.
Imagine, this is the code:
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:
create an new void method, wich accepts the result as parameter:
and call from inside the
onResponseRevieve
-method:Hope that helps.