Completion handlers in Java?

completionhandler, java

Solution

Interface types, in general. You can use `Runnable` (which is an `interface`) as Rob suggested if your handler has no parameters and a `void` return type. But it's simple enough to define your own:

interface CompletionHandler {
    public void handle(String reason);
}

and then to pass it to your own class:

something.setCompletionHandler(new CompletionHandler() {
    @Override
    public void handle(String reason) {
        ...
    }
});

In the other class:

void setCompletionHandler(CompletionHandler h) {
     savedHandler = h;
}

and then call it just by calling the method:

savedHandler.handle("Some mysterious reason");

This sort of thing is done for "listeners" in Java Swing and Android libraries all over the place; see `View.OnClickListener`, for example.

(P.S. I believe that Java 8 lambdas will be usable with all of these interface examples.)

Problem

I've been coding for iOS and I'm quite familiar with the concept of blocks in Objective-C. Now I'm leaning Java for Android and trying to convert some apps from Android to iOS. I read that there no perfect equivalent of blocks in Java, so I'd like to know what is the best alternative to implement completion handlers or anything that could work similarly.

Original source