Working on my first Java project I can't seem to get around this probably basic problem: In a JavaFX
application I have a DAO
class, which starts a service
to get values from a mysql
db, builds an object from it and returns the object to the caller. But the object never gets build, because the return happens before the service has succeeded.
public IQA getQA(int id) throws SQLException {
try {
GetQuizService getQuizService = new GetQuizService();
getQuizService.restart();
getQuizService.setId(id);
getQuizService.setOnSucceeded(e -> {
this.quiz = getQuizService.getValue();
});
} catch (Exception e) {
System.err.println(e);
}
return quiz;
}
The service works fine, inside the onSucceeded action the object is present, but how can I make the return wait until the service has finished?
As requested here's a minimal version of the GetQuizService
public class GetQuizService extends Service<Quiz> {
private int id;
private Quiz quiz;
public void setId(int id) {
this.id = id;
}
@Override
protected Task<Quiz> createTask() {
return new Task<Quiz>() {
@Override
protected Quiz call() throws Exception {
// Severall calls to db here, Quiz object gets constructed
return quiz;
}
};
}
}