cxzp
cxzp

Reputation: 672

should you create new Async Tasks for every different call or use the same one

So I have an app that will make multipe HTTP Post/Gets

E.G. Login, getThisData, getThatData, sendThis, sendThat

Is it better to have a seperate AsyncTask to handle each one

Or one async task and process them differently with a switch in onPostExecute and doInBackground

Cheers

Upvotes: 3

Views: 1916

Answers (4)

Ben Lee
Ben Lee

Reputation: 3418

If you want to create one instance of AsyncTask, and execute() it several times, no:
Execute AsyncTask several times

If you are asking about designing: whether you should write one class to get different kind of data? It really depends on your circumstances:
If these HTTP call supposed to be sequential, you can put them in one AsyncTask class.
If they have lot in common, just point to different URIs, you can write a call(String uri) method, and invoke that method in your AsyncTask. This case, I think one AsyncTask is also enough.

Upvotes: 0

Aksel Fatih
Aksel Fatih

Reputation: 1449

Short answer is yes you should create a new AsncTask for each call.

And if you interested, the long answer is;

According to the Android's Asynctask documentation,

  • The goal of the AsyncTask is to take care of thread management for you and you should not worry about the threading mechanisms.
  • The Android Platform handles the pool of threads to manage the asynchronous operations. AsyncTasks are like consumables. The task can be executed only once (an exception will be thrown if a second execution is attempted.)

Happy asynchronous coding! :-)

Upvotes: 7

pfairbairn
pfairbairn

Reputation: 451

You'll probably want to separate them, especially if their functionality in the pre/post executes differs. Try to organize your code into logical blocks. For example, if you have an Async Task to Login, and an Async task to, for example, download lots of document data via JSON, they will want separate Async tasks.

However, lets say you have two separate API calls that return similar or partially the same data - if one returned the details of a file (name, size) and the other returned the same data but was a revision of a file - you could switch these in the same ASYNC because the post execute is going to perform the same (or partially the same) code to extract data from the JSON.

Upvotes: 0

Ritaban
Ritaban

Reputation: 773

It depends on whether the tasks are independent on each other or whether they are interrelated. If independent you can handle this through the same async. For ex if you need some data from your login response and pass that value to getthis task you better use separate async. Make login a separate async, getthis ,get lthat sendthis sendthat can be in one async.

Upvotes: 0

Related Questions