Reputation: 1932
I have an app underdevelopment and I need to do 3 HTTP POSTs in sequence. What is the best way to implement this ? Should I
Make each HTTP Post in it own Async Class and daisy chain the Async classes(i.e. call the second async from the onPostExecute of the first Async)
Put all the HTTP POSTs in the doInBcakGround of a single Async.
I know how to do a HTTP POST request and I am using the OKHTTP lib. I just would like to know that the best practice it for multiple POSTs in sequence.
Cheers
Upvotes: 4
Views: 1946
Reputation: 18977
Put all the HTTP POSTs in the doInBcakGround of a single Async.
because all your posts handle in one module.
dose not have overhead of creating asyntask and GC may not call as many as your first.
you do not need to check internet connection 3 times you have to check it one time
all exception handles one time but in approach 1 you have to copy and paste all exception handler that may occurs. and always recommended not to repeat yourself. if you can do something to not copy and paste codes, do it.
At the end I prefer approach 2.
Upvotes: 0
Reputation: 4620
Your first approach will be better and quite modular as you can keep the track of anything in your application.In the three different AsyncTask
you can have a check in postExceute()
that which AsyncTask
is done with its work (more easily and precisely) AND
>>>>>In case if the application gets Crashed
then which of the httpPost
failed. However , the second one will make your code messy and you will be unable to track on getting Exception
that which httpPost
request failed(in a straight forward way though).
So Launching your second AsyncTask from onPostExecute of your first task will be better approach.
See here too : Calling an AsyncTask from another AsyncTask
Upvotes: 3
Reputation: 495
Both 1 and 2 approaches make app ANR, so better to for other approach.
You can use ExecutorService that executes each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods.
Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.
here is more deatias http://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.html
Upvotes: 0