Exercise: Exercise 5 - leveraging Loaders

My brain is broken. Damnit… What is up with multithreading? This last tutorial is absolutely silly. there are 23 different todo’s with crazy looking syntax. Once again, I need to rant a bit so I can make sense of this madness.

Summary

The key to android development is making the main (UI) thread as lightweight as possible. That means a developer should try to offload none UI tasks to different threads. In my latest tutorial, the best way to achieve that is through the use of loaders.

AsyncTask

AsyncTask is a threading library that creates a class that handles tasks and operations that need to be done in the background asyncronously. Ideally, these should be short operations.

Asynchronous task is defined by three gnereric types 

- Params - 
- Progress
- Result

Asynchronous consists of four steps 

- onPreExecute
- doInBackground
- onProgressUpdate
- onPostExecute

Problems with AsyncTask

It is possible that AsyncTask can run duplicate threads in the background if a user restarts an activity. Basically, if the user rotates their screen or something, and the activity is destroyed and then recreated, then the original AsyncTask will continue to run despite the activity no longer existing.

Fragments

If everything I wrote isn’t enough, this lesson also discusses activities and fragments interchangably. There is such a thing called fragmentActivity. These are most commonly used to create multi-pane UI. It can be thought of as a sub-activity with its own lifecycle.

Bundles

In this exericise, bundle is specifically used to pass load data for later. Whe n the screen rotates onSaveInstanceState(Bundle outstate) method is invoked and the activity is destroyed. We then call onCreate(Bundle savedInstanceState)` method to create the activity using the data from the previous activity.

Loaders

Some of the challenges that arise when dealing with multiple threads is them communicating with one another. For example, threads can continue to run despite the Main UI Thread stopping for whatever reason. As a result, loaders can help improve the user experience by managing the various threads.

One stack overflow post says that the java framework could use java map, however, map is not guaranteed to store serialiable objects. Bundles restricts the type of objects to ensure serializability.

AsyncTaskLoader is a lot like AsyncTask except it is a bit better. It behaves within the lifecycles of fragments/activities.

- loaders persist and chache results across configuration changes to prevent duplicate queries
- Loaders can implement an observer to monitor changes in the underlying data source such as `CursorLoader` and `ContentObserver` which trigger reloads when data changes.