Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42690

Guideline to choose among AsyncTaskLoader and AsyncTask to be used in Fragment

Look at LoaderCustomSupport (Use AsyncTaskLoader) and FragmentRetainInstanceSupport (Use Thread, almost equivalent to AsyncTask)

Both examples have the following similarities.

However, there are differences.

AsyncTaskLoader

AsyncTask

Is there any guideline, or checklist to look at, to make a decision on whether to choose AsyncTaskLoader or AsyncTask, to do a time-consuming loading task and update the result to Fragment's UI?

Upvotes: 30

Views: 10935

Answers (2)

stinepike
stinepike

Reputation: 54672

your question made me interested and tried sometimes to look into the differences. Here i am writing my observations.

  1. For the premature termination the asynchronous task using AsyncTask will continue running in its thread. The processing of the results can soon lead to unrequested results while AsyncTaskLoader handle the premature termination of the activity

  2. AsyncTaskLoader handles activity configuration changes (IE when the user rotates the screen).

  3. AsyncTaskLoader is intended load data for DataAdapters so for this purpose it is best to use AsyncTaskLoader But if you need to change UI (specially fragments) after task completion it is better to use AsyncTask as you can't change fragments in onLoadFinished of AsynTaskLoader.

So to me the usage depends on your task. and if the above 3 points doesnt bother you then the performance is same ( haven't found any documents though , but in this case asynctaskloader is recommended :S)

some related links

AsyncTaskLoader vs AsyncTask

http://andreas-kluck.blogspot.com/2012/02/asynctask-and-asynctaskloader.html

Upvotes: 26

cephus
cephus

Reputation: 2027

AsyncTaskLoaders, like all Loaders, are intended to solve the rotation problem, which is when an AsyncTask is created on an Activity, then the device is rotated before the task has completed that AsyncTask will be lost with the destruction of the Activity.

It's true that all Loaders currently don't support publishing progress, so if this is a requirement for your situation then you should consider an alternative. If rotation, or any other event that causes the Activity to be destroyed, isn't an issue then just use an AsyncTask, otherwise you might want to use a Service, and register a binder to push progress messages back and forth.

Service and Binder messages are kind of a pain though, in my opinion. I find a much easier solution is to use LocalBroadcastManager to send progress broadcasts from an IntentService (or AsyncTaskLoader) and have a BroadcastReceiver in the Activity receive the broadcast and display the progress.

Upvotes: 0

Related Questions