Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a value from asynchronous call to run method

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.

like image 874
LeenaLatesh Avatar asked Aug 05 '13 05:08

LeenaLatesh


2 Answers

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();
like image 173
René Link Avatar answered Sep 26 '22 20:09

René Link


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
            }
        });
like image 40
aim Avatar answered Sep 25 '22 20:09

aim