Completion handlers in Java?

I encoded iOS and I am very familiar with the concept of blocks in Objective-C. Now I'm leaning towards Java for Android and trying to convert some apps from Android to iOS.

I read that there is no perfect block equivalent in Java, so I would like to know what is the best alternative for implementing completion handlers or anything that might work in a similar way.

+8
java completionhandler
source share
2 answers

Types of interfaces, 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 is simple enough to define your own:

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

and then pass it to your class:

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

In another class:

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

and then call it by calling the method:

 savedHandler.handle("Some mysterious reason"); 

Things like this are done for listeners in Java Swing and Android libraries everywhere; see View.OnClickListener , for example.

(PS I believe Java 8 lambdas can be used with all of these example interfaces.)

+17
source share

You can run runnables. Obviously, the equivalent of blocks will require lambdas, which come in Java 8, but who knows how long Android has been supporting them (they still use JUnit 3.8).

There are many places in Android where things like blocks are done, for example:

  this.currentConditionsActivity.runOnUiThread(new Runnable() { @Override public void run() { currentConditionsActivity.onLocationChanged(...); } }); instrumentation.waitForIdleSync(); setupViewElements(); 

As you can see, you need to instantiate an anonymous class, but in most IDEs the stupidity of the template is facilitated by autocompletion. This was done in Android Studio, and it all happened after executing the new Runnable () (and if you dump the code, it even shows a syntax similar to what lambdas will have).

So the state is for now. Not so bad many do it ...

+3
source share

All Articles