I have a method that has to return a boolean value. The method has an asynchronous call to run method. In the run method, i have to set variable in the enclosing method. below is my code.
private boolean isTrue() {
boolean userAnswer;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
userAnswer = MessageDialog.openQuestion(new Shell(), "some message", "some question?");
}
});
return userAnswer;
}
This code gives error -- "userAnswer" has to be final, and if i make it final i cant assign a value to it. Please suggest a way to handle this scenario.
You can use the java.util.concurrent.FutureTask<V>
if you need to adapt a Callable<V>
to a Runnable
.
public class UserQuestion implements Callable<Boolean> {
private String message;
private String question;
public UserQuestion(String message, String question) {
this.message = message;
this.question = question;
}
public Boolean call() throws Exception {
boolean userAnswer = MessageDialog.openQuestion(new Shell(),
message, question);
return Boolean.valueOf(userAnswer);
}
}
UserQuestion userQuestion = new UserQuestion("some message", "some question?");
FutureTask<Boolean> futureUserAnswer = new FutureTask<Boolean>(userQuestion);
Display.getDefault().asyncExec(futureUserAnswer);
Boolean userAnswer = futureUserAnswer.get();
There'are a lot of patterns to accomplish this. Maybe the easiest use some sort of callback function, for example:
interface Callback {
void onSuccess(boolean value);
}
private boolean isTrue(final Callback callback) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
boolean userAnswer = MessageDialog.openQuestion(new Shell(), "some message", "some question?");
callback.onSuccess(userAnswer);
}
});
}
And invoke method like this:
isTrue(new Callback() {
@Override
public void onSuccess(boolean value) {
// do some stuff
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With