Nepster Nepster - 2 months ago 13
iOS Question

how to implement blocks in android

In IOS we use blocks when we want to handle an action when a particular situation occur
.

Is there a way like this in android to handle situation onCompletion and we can add where ever it is.

Like AsyncTask methods it knows when work is finish . it executes onPostExecute. How we can create this type of method when a particular situation reach and we handle it like .

Today i find a way which behave like Blocks in IOS

BaseAsyncTask(new Callback(){

onPostResult(string result)
{
// do whatever you want to do with the result got from asynctaks
}
});


it is a delegate and it calls when it reaches a particular situation..

Am i right that the above code is block in android as we do in IOS. or there any other way of creating blocks in android.

Answer

It seems that you have two questions in your question so I will answer them both

Is there a way like this in android to handle situation onCompletion and we can add where ever it is? How we can create this type of method when a particular situation is reached?

Yes there is a way. I have asked the same thing once here.

In this cases, you use Runnable. You use it like so:

//creating a runnable block
Runnable block = new Runnable() {
    @Override
    public void run() {
        //code here
    }
};

//passing it on arguments
doSomething(block); //just like a normal variable

//using it on the method
public void doSomething(Runnable block) {
    block.run();
}

Your 2nd question:

BaseAsyncTask(new Callback(){

    onPostResult(string result)
    {
        // do whatever you want to do with the result got from asynctaks
    }
});

Am i right that the above code is block in android as we do in IOS. or there any other way of creating blocks in android.

Yes in my opinion, the object Callback behaves the same as the blocks in Objective C as I have shown in my previous examples. When the async task is completed (the result is already available) then that Callback is called. Probably like so:

callback.onPostResult();

Just for your information, the Objects Runnable and Callback are java interfaces. More on interfaces here. If you do not need extra parameters for your callback, you can just use the Runnable so as to avoid reinventing the wheel. But if there is something special, i.e. you want to pass paramters to the callback, then you can create your own interface and use it like a Runnable.

Comments