Call task's updateProgress

房东的猫 提交于 2019-12-11 03:57:15

问题


I was reading the documentation for the class Task

    final Task<Void> task = new Task<Void>() {
        @Override public Void call() {
            for(int i=0;i<datesAndStudies.length;i++){
                updateProgress(i,datesAndStudies.length);
                DoSomething something = new DoSomething();
                something.VeryLongAndTimeConsumingMethod(i);
            }
            return null;
        }
    };

And I notice that updateProgress is protected and workdone/totalwork are both defined as public final ReadOnlyDoubleProperty.

Is there a way/workaround to update/call updateProgress or edit those values(workdone/totalwork) from the method: VeryLongAndTimeConsumingMethod(int i) in the class DoSomething ?


回答1:


Even if updateProgress(...) were public, you'd have to pass a reference to the Task to your DoSomething class, which creates some really ugly coupling. If you have that level of coupling between your Task implementation and your DoSomething class, you may as well just define the long, time consuming method in the Task subclass itself, and get rid of the other class:

final Task<Void> task = new Task<Void>() {
    @Override
    public Void call() {
        for (int i=0; i<datesAndStudies.length; i++) {
            veryLongAndTimeConsumingMethod(i);
        }
        return null ;
    }

    private void veryLongAndTimeConsumingMethod(int i) {
        // do whatever...
        updateProgress(...);
    }
};

To preserve your decoupling, just define a DoubleProperty representing the progress in DoSomething, and observe it from the Task, calling updateProgress(...) when it changes:

public class DoSomething {
    private final ReadOnlyDoubleWrapper progress = new ReadOnlyDoubleWrapper(this, "progress");
    public double getProgress() {
        return progress.get();
    }
    public ReadOnlyDoubleProperty progressProperty() {
        return progress.getReadOnlyProperty();
    }
    public void veryLongAndTimeConsumingMethod(int i) {
        // ..
        progress.set(...);
    }
}

Then:

final Task<Void> task = new Task<>() {
    @Override
    public Void call() {
        for (int i=0; i<datesAndStudies.length; i++) {
            DoSomething something = new DoSomething();
            something.progressProperty().addListener(
                (obs, oldProgress, newProgress) -> updateProgress(...));
            something.veryLongAndTimeConsumingMethod();
        }
    }
}


来源:https://stackoverflow.com/questions/23701639/call-tasks-updateprogress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!