简体   繁体   中英

Correct way of attaching progress listeners to the objects in the list

I'm making a JavaFX desktop application which allows user to solve problems remotely. It downloads files to the cloud storage and uploads the result from there (which may seem a bit odd but is not the case now).

I've got a class representing a problem (Model) and a Controller class, which periodically accesses the cloud. I keep track on the progress of downloading/uploading each problem with the help of ProgressListener class from the cloud storage API. I needed a separate instance for every problem in the list (so that they can download simultaneously), so I made an instance variable for the progress listener in the Problem class. The thing is, at the end of each download/upload I need to perform some actions (like talking to the cloud storage), and writing all this code in the Problem class (or even calling a Controller method, for that matter) doesn't seem like a good idea to me.

Problem class looks something like this:

public class Problem {
    private SimpleIntegerProperty progress;
    private ProgressListener progressListener;
    public Problem() {
        progressListener = new ProgressListener() {
            @Override
            public void updateProgress(int bytes,int total) {
                progress.set(bytes);
                if (bytes==total) {
                    // do smth in cloud storage
                }
            }
        }
    }
}

My question is how to implement this kind of interaction properly.

I think the controller class is the natural place for keeping track of the download progress. So there I would create the progress listeners:

public class Controller {

    public ProgressListener createProgressListener(Problem problem, Consumer<Problem> onDownloadComplete) {

        return new ProgressListener() {

            @Override
            public void updateProgress(int bytes, int total) {
                if (bytes == total) {
                    onDownloadComplete.accept(problem);
                }
            }
        };
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM