does anyone know how I can solve the following problem. I want to return a String from a callback, but I get only “The final local variable s cannot be assigned, since it is defined in an enclosing type”, because of final.
public String getConstraint(int indexFdg) {
final String s;
AsyncCallback<String> callback = new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
public void onSuccess(String result) {
s = result;
}
};
SpeicherService.Util.getInstance().getConstraint(indexFdg, callback);
return s;
}
The whole point of an asynchronous callback is to notify you of something that happens asynchronously, at some time in the future. You can’t return
sfromgetConstraintif it’s going to be set after the method has finished running.When dealing with asynchronous callbacks you have to rethink the flow of your program. Instead of
getConstraintreturning a value, the code that would go on to use that value should be called as a result of the callback.As a simple (incomplete) example, you would need to change this:
Into something like this:
Edit
A popular alternative is the concept of a future. A future is an object that you can return immediately but which will only have a value at some point in the future. It’s a container where you only need to wait for the value at the point of asking for it.
You can think of holding a future as holding a ticket for your suit that is at the dry cleaning. You get the ticket immediately, can keep it in your wallet, give it to a friend… but as soon as you need to exchange it for the actual suit you need to wait until the suit is ready.
Java has such a class (
Future<V>) that is used widely by the ExecutorService API.