Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

For the More Curious: Alternatives to AsyncTask


For the More Curious: Alternatives to AsyncTask


If you use an AsyncTask to load data, you are responsible for managing its lifecycle during
configuration changes, such as rotation, and stashing its data somewhere that lives through those
changes. Often, this is simplified by using setRetainInstance(true) on a Fragment and storing the
data there, but there are still situations where you have to intervene – and code you have to write to
ensure that everything happens correctly. Such situations include the user pressing the Back button
while the AsyncTask is running, or the fragment that launched the AsyncTask getting destroyed during
execution by the OS due to a low-memory situation.


Using a Loader is an alternative solution that takes some (but not all) of this responsibility off your
hands. A loader is designed to load some kind of data (an object) from some source. The source could
be a disk, a database, a ContentProvider, the network, or another process.


AsyncTaskLoader is an abstract Loader that uses an AsyncTask to move the work of loading data to
another thread. Almost all useful loader classes you create will be a subclass of AsyncTaskLoader. The
AsyncTaskLoader will do the job of fetching the data without blocking the main thread and delivering
the results to whomever is interested.


Why would you use a loader instead of, say, an AsyncTask directly? Well, the most compelling
reason is that the LoaderManager will keep your component’s loaders alive, along with their data,
between configuration changes like rotation. LoaderManager is responsible for starting, stopping, and
maintaining the lifecycle of any Loaders associated with your component.


If, after a configuration change, you initialize a loader that has already finished loading its data, it can
deliver that data immediately rather than trying to fetch it again. This works whether your fragment
is retained or not, which can make your life easier because you do not have to consider the lifecycle
complications that retained fragments can introduce.

Free download pdf