Search code examples
javarecursioncancellation

How to implement "Cancel" button for a recursive algorithm?


I'm trying to implement a "Cancel" button for an algorithm in a folder synchronization app. The algorithm goes recursively through a directory structure specified by the user, puts its files and directories into a TreeView, and marks them depending on whether they are new, deleted, changed, or unchanged in relation to their equivalents in the other folder. Simplified code for reference:

fillInTreeView(File x, TreeItem root) {
    if (x.isFile()) {
        newBranch = makeBranch(x.getName(x.getNameCount() - 1).toString(), root);
        assignMark(newBranch);
    } else {
        newBranch = makeBranch(x.getName(x.getNameCount() - 1).toString(), root);
        assignMark(newBranch);
        fillInTreeView(x, newBranch);
    }
}

What I'm shaky at are the implications of that "Cancel". If I make it delete everything in the tree from the top, won't the function continue to add new stuff anyway, calling itself from the files that the cancel algorithm hasn't reached yet, making the whole button pointless? I figured I'd rather ask first rather then spend several days trying to implement it, only to have to ask later and rediscover America.


Solution

  • Try it Like this:

    private static boolean cancelled = false;
    
    fillInTreeView(File x, TreeItem root) {
       if(cancelled) return;
       if (x.isFile()) {
            newBranch = makeBranch(x.getName(x.getNameCount() - 1).toString(), root);
            assignMark(newBranch);
        } else {
            newBranch = makeBranch(x.getName(x.getNameCount() - 1).toString(), root);
            assignMark(newBranch);
            fillInTreeView(x, newBranch);
        }
    }
    
    /*Your CLick-Listener*/
    public void onClick(){
           cancelled = true;
    }