Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern to make AsyncTask "procedural"

I am using AsyncTask in a lot of places without issues.

Now with Honeycomb, all network i/o needs to be in thread separate from the UI thread, which in a lot of cases needs AsyncTasks in places, where before a synchronous network connection was well suited (Honeycomb will throw an Exception for any network i/o on the main/ui thread).

Now I would basically like to get something like Object result = MyAsyncTask().execute() are there good patterns for this?

I've found AsyncTask Android - Design Pattern and Return Values which makes sense and is also how GWT does things, but somehow this sounds like wagging the dog by the tail (and then it may just be me who's brain needs some more twisting).

like image 833
Heiko Rupp Avatar asked Jun 13 '11 08:06

Heiko Rupp


3 Answers

Yup. You're close. Try

Object result = MyAsyncTask().execute().get();
like image 199
Tyler Collier Avatar answered Oct 20 '22 10:10

Tyler Collier


I'm sure that you're not wanting to perform a synchronous network transaction on the UI thread, right?

The pattern that I use is to hold state in the Activity (which implements a receiver), then call AsycTask which performs a callback to your activity in onPostExecute() (i.e. fire an Intent which your activity is listening for). Your activity can then update the state according to extras in the intent, and continue processing. It's basically a state machine held in your Activity which performs your login and other functions. All of the network I/O stuff is performed in AsycTask instances which cause the state to be updated as they complete.

like image 28
Mark Allison Avatar answered Oct 20 '22 09:10

Mark Allison


If you just want to block your thread, while other thread does the job, you could consider writing your own task abstraction. I am thinking of something like

public class MyTask <T>  {
    // define executor here
    public T execute(Callable<T> c) {
        Future<T> t = executor.submit(c);
        return t.get();
    }
 }
like image 30
Alex Gitelman Avatar answered Oct 20 '22 10:10

Alex Gitelman