【问题标题】:How to wait for a JavaFX Service to finish before returning data in caller?如何在调用者返回数据之前等待 JavaFX 服务完成?
【发布时间】:2019-08-01 01:12:24
【问题描述】:

在处理我的第一个 Java 项目时,我似乎无法解决这个可能是基本问题:在 JavaFX 应用程序中,我有一个 DAO 类,它启动一个 service 以从 mysql 获取值db,从中构建一个对象并将该对象返回给调用者。但是对象永远不会被构建,因为返回发生在服务成功之前。

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;
}

服务工作正常,在 onSucceeded 操作中对象存在,但我怎样才能让返回等到服务完成?

根据要求,这里是 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;
            }
        };
    }
}

【问题讨论】:

  • GetQuizService 代码在哪里?
  • GetQuizService 代码长达 100 多行......它也可以正常工作。当我在 getQuizService.setOnSucceeded 中执行 syso 时,我得到 this.quiz 就好了。只有在 return 语句上我得到一个空值。

标签: java mysql javafx service


【解决方案1】:

您的代码中的问题是,您的服务方法是异步执行的。

您应该返回 Task&lt;Quiz&gt; 而不是 quiz 并在收到结果时使用它来更新您的前端(我需要很少的信息来为您创建一个合适的示例)。

另一种选择是将回调传递给您的服务,当收到结果而不是返回测验时调用该回调。

public void getQA(int id, QuizReceiver callback) throws SQLException {
    try {
        GetQuizService getQuizService = new GetQuizService();
        getQuizService.restart();
        getQuizService.setId(id);
        getQuizService.setOnSucceeded(e -> {
            callback.quizReceived(getQuizService.getValue());
        });         
    } catch (Exception e) {
        System.err.println(e);
    }
    return quiz;
}
public interface OuizReceiver {
    void quizReceived(IQA quiz);
}

【讨论】:

  • 谢谢!最后我认为这指向了项目中的一个设计问题,我应该解决这个问题。
  • 再次感谢塞缪尔!对于任何感兴趣的人,我发现this thread 解决了我面临的情况
猜你喜欢
  • 1970-01-01
  • 2020-04-17
  • 2010-10-19
  • 1970-01-01
  • 2021-10-13
  • 2019-06-11
  • 1970-01-01
  • 2019-03-03
  • 1970-01-01
相关资源
最近更新 更多