Android Architecture Components : Observerers, View Model & Live Data

Dhananjay Trivedi
5 min readFeb 18, 2019
— Source :

Remember the basic components of Android? Activity, Content Provider, Services and Broadcast Recievers? Google introduced new components as a part of Android Jetpack which are very much similar to the previous one but comes with ease of development for us developers. In this article, we are going to focus on Android Architecture Compnents.

Important Point while Importing libraries:

Checkout Android Dependencies to use Architecture Components in your project. Also, if you will import Architecture Components in your project, you have to upgrade your libraries to Android X by updating gradle.properties file by adding these two lines : “ android.useAndroidX=true android.enableJetifier=true”.

Once you do update your project to AndroidX, you will have to update your layout files according to the Widgets provided in AndroidX, and also your Java/Kotlin files using the AndroidX classes so watch out before running to Fatal Crashes.

Do gradle sync, and run your app after importing the libraries to see if there are no comtability issues between libraries.

1. Lifecycle Aware Components

You are aware of the Android Activity lifecycle, so our Activity/Fragment is the LifeCycleOwner and this lifecycle listens / observers LifeCycleObserver for change in data in the observer and updates itself automatically. The LifeCycleObserver is responsible for getting the data and performing the operations, not your Activity. Clean and good architecture isn’t it?

LifecycleOwner provides Lifecycle Status to LifeCycle aware components such as observer, LifeCycleObserver responds to changes in the UI and perform operations.

Example:

Here is the MainActivity file, and you also have to create a seperate Observer Class, here is how

You can add more events as per your requirements. I have just shown 3 here for example.

2. View Model

In everyday scenario, you Activity has to

  • Display UI Data
  • React to User Action
  • Handle Android Operating System Communication
  • Load data from network / database or sometimes, all of the above.

If you write all your code in single Activity file your code is messy and non maintainable. Also, if you are already writing different classes to do different operations then we all have faced the issue to update back the UI which is a big pain in the ass where you are writing a lot of boiler plate code.

View Model helps in taking the load off your Activity file and also updating the UI is done automatically so you dont have to write that extra code to update the UI once your asynchornous task is completed.

In short, View Model provides data to the UI, and also contains the logic of how task have to be executed once they are triggered from the UI. This helps in seperating the UI code and Business Logic of your application.

The biggest strength that comes with View model is that it survives the configuration changes such as Screen Rotation which has been a big pain in the ass for developers, to write that extra boiler plate code to save and retrieve data each time the user rotates his device for all your activities. I personally hate doing that.

How ViewModel survives the configuration changes?

Take a look at the Activity Life Cycle Diagram.

When Activity is created with onCreate() is ViewModel is linked with your Activity. Then the activity goes through the life cycle methods like onStart() onResume(). If data is changed in the activity, it is updated in the ViewModel, but not automatically.

Now when the screen is rotated this activity goes through onPause() onStop() and onDestroy() methods and is completely teared down and is again recreated and goes thought the same life cycle methods. This time, the instance of the view model left by the previous activity is passed onto this new Activity and hence the data is preserved between the rotated activities without writing any extra code.

OnSaveInstanceState() which we have been using, helps only to store small data like String and primitive data type values, but for storing larger data such as bitmap or complex data strucutures it will not work well.

So key take away points :

  1. Survives configuration changes
  2. Useful to store large / complex data like Bitmaps
  3. Store and manage UI related data
  4. Helps in updating UI from Async operations.

View-Model Demonstration

Kotlin Activity File, lets say you want to upload the Image on-click of the imageView, so we just call a function defined in the view-model from our Activity file, and the view-model will take care of doing the operations and updating the UI once the task is completed with help of LiveData
Activity ViewModel class containg the function you called from Activity

3. Live Data

We have been doing great so far, as we are able to seperate the processing logic of our app from our app’s UI logic. So once the task is done, we have to update back the UI right? how do we go about that? Well till now we had the option to use Interfaces, Broadcast Recievers where we had to again write some boiler plate code to do something once the task is completed in the background. Google introduced LiveData to update the UI automatically once our data gets updated.

How LiveData works?

Our ViewModel has the LiveData object and our UI keeps observing the changes in this LiveData. Since this LiveData is with ViewModel, which survives the configuration changes, our LiveData survives too and the data is automatically updated if our Activity undergoes any configuration changes.

Let’s say you perform a long running task such as fetching data from server and you have to update the UI once you get the data, but in the meantime you move away from the Activity, your Activity goes throught onPause() and onStop(), and your Activity stops observing the LiveData hence once the task is completed in the background, your data will not be thrown back to your UI even though it’s not there causing a memory leak.

Demonstration

  • First is the Activity file where we define the UI Logic, and observe the value of Mutable LiveData from the ViewModel.
  • Second file is the ViewModel which contains our business logic, and updates the LiveData once the task is completed.
In the Activity, after setting ViewModel, create a LiveData variable and observe it for changes, if changes occurs, update the UI

Key Points

  • LiveData is observable data holder class
  • Keeps data and allows it to be observed for updation
  • Should start observing once the onCreate() method of Activity is called to avoid any redudant calls to ViewModel
  • It helps to keep UI in sync with data
  • Destroyed automatically when LifeCycleOwner is destroyed
  • No memory leaks
  • Can be used by multiple resources

That’s All Folks, Will be adding more here as I learn more about Architecture Components!

--

--