.: Android runnables and iOS code blocks :.

Every programming language has something interesting to learn. The difference between Objective-C and Java is huge, I don't even like to compare them, but when you change your environment you need to know what your languange supports. Many Android developers there are used to Web and Destktop solutions try to think that the same solution can solve their problems in the mobile world. Maybe they can, but if efficiency is a concern, solving is not always everything. The path to excellency requires both efficacy and efficiency.

Anyway, I was going to write about runnables and code blocks. The iOS developers are probably used to code blocks, since they are part of the language and used widely, specially to use the full potential of the GCD. But about Java? In Java we have callables (link) and runnables (link). I will write about executors (link) another day, since they are part of the same package.

In this guide "Designing for Responsiveness" (link), you will learn that one way to avoid an ANR is to create a child thread to perform the background computation that would block the main thread. But you can't do everything in threads. Some of your code needs to execute on the main thread (like invalidating a view) and that's why runnables are useful.

Android Activities have a method to execute a runnable on the main thread called runOnUiThread (link). If you are suffering to make your threads to work, like when you show a Toast it causes the exeption "Can't create handler inside thread that has not called Looper.prepare()", writing it in a runnable and then calling it on the UI thread will solve it.

Also, many code that is basically copy/paste could be better written if enclosed within a runnable. Since a runnable is an object, you can also use them as parameters to other child objects of the activity, much like delegates used in iOS. In Objective C we control how to dispatch code blocks, the queue to use them, if they will execute synchronously, assynchronously, etc. In Java, executors will do the trick. I hope you find them usefull.

.: Post a Comment :.