Android Architecture Components

During the Google I/O 2017, there were a lot of new announcements for the Android Platform. One of the announcements was the new architecture guidelines for Android! This is a welcome addition to the Android platform. They reduce the amount of boilerplate and repetitive code, leaving you to focus on the core functionality of your application. These components can be used in isolation but work really well when used together.

Now, I know this might not be new to many of us who have been doing Android for a while now. But nonetheless, I decided to visit this area and write a simple and detailed article about them.

Now, we will look at these three components.

Room

LiveData

ViewModel

Room

I have already written some articles about Room, you can go through them to understand it better. But let me shed some light here also. Room is a new way to create databases in your Android apps. Room eliminates a lot of the boilerplate code you had to write previously to store data in your apps. Room is an ORMbetween Java classes and SQLite. With Room, you no longer need to use Cursors and Loaders.

LiveData

LiveData allows you to observe changes to data across multiple components of your app without creating explicit, and rigid dependency paths between them. When you combine LiveData with Room, it gives you the ability to receive automatic database updates which can be difficult to achieve by just using a standard SQLiteDatabase.

1

2

3

4

5

6

eventDao=eventDatabase.eventDao();

eventDao.getEvents().observe(this,events->{

Log.d(TAG,"Events Changed:"+events);

adapter.setItems(events);

});

LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.

The advantages of using LiveData

Using LiveData provides the following advantages:

Ensures your UI matches your data state

LiveData follows the observer pattern. LiveData notifies Observer objects when the lifecycle state changes. You can consolidate your code to update the UI in these Observer objects. Instead of updating the UI every time the app data changes, your observer can update the UI every time there’s a change.

No memory leaks

Observers are bound to Lifecycle objects and clean up after themselves when their associated lifecycle is destroyed.

No crashes due to stopped activities

If the observer’s lifecycle is inactive, such as in the case of an activity in the back stack, then it doesn’t receive any LiveData events.

No more manual lifecycle handling

UI components just observe relevant data and don’t stop or resume observation. LiveData automatically manages all of this since it’s aware of the relevant lifecycle status changes while observing.

Always up to date data

If a lifecycle becomes inactive, it receives the latest data upon becoming active again. For example, an activity that was in the background receives the latest data right after it returns to the foreground.

Proper configuration changes

If an activity or fragment is recreated due to a configuration change, like device rotation, it immediately receives the latest available data.

Sharing resources

You can extend a LiveData object using the singleton pattern to wrap system services so that they can be shared in your app. The LiveDataobject connects to the system service once, and then any observer that needs the resource can just watch the LiveData object.

ViewModel

A ViewModel is not a new concept, nor is it neccesarily an Android concept. The name ViewModel came from the MVVM pattern designed by Microsoft in around 2005. With the new Architecture Components, one of the new classes is the ViewModel class.

ViewModels are responsible for preparing data for the View. They expose data to any view that is listening for changes.

For example, if you need to display a list of users in your app, make sure to assign responsibility to acquire and keep the list of users to a ViewModel, instead of an activity or fragment, as illustrated by the following sample code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

publicclassMyViewModelextendsViewModel{

privateMutableLiveData<List<User>>users;

publicLiveData<List<User>>getUsers(){

if(users==null){

users=newMutableLiveData<List<Users>>();

loadUsers();

}

returnusers;

}

privatevoidloadUsers(){

// Do an asyncronous operation to fetch users.

}

}

You can then access the list from an activity as follows:

1

2

3

4

5

6

7

8

9

10

11

publicclassMyActivityextendsAppCompatActivity{

publicvoidonCreate(Bundle savedInstanceState){

// Create a ViewModel the first time the system calls an activity's onCreate() method.

// Re-created activities receive the same MyViewModel instance created by the first activity.

MyViewModel model=ViewModelProviders.of(this).get(MyViewModel.class);

model.getUsers().observe(this,users->{

// update UI

});

}

}

The ViewModel class in Android has some specific facts you should keep in mind when using it:

A ViewModel can retain its state across Activity configuration changes. The data it holds is immediately available to the next Activity instance without needing to save data in onSaveInstanceState() and restore it manually.

A ViewModeloutlives the specific Activity or Fragment instances.

A ViewModel allows easy sharing of data across Fragments (meaning you no longer need to coordinate actions via an activity).

A ViewModel will stay in memory until the Lifecycle it’s scoped to goes away permanently – in the case of an Activity, once it finishes; in the case of a Fragment, once it’s detached.

Since a ViewModel outlives the Activity or Fragment instances, it shouldn’t reference any Views directly inside of it or hold reference to a context. This can cause memory leaks.

If the ViewModel needs an Application context (e.g. to find a system service), it can extend the AndroidViewModel class and have a constructor that receives the Application in the constructor.

In Summary

The new Android Architecture Components address common scenarios that we haven’t been able to handle easily before, reducing the amount of boilerplate and repetitive code, leaving you to focus on the core functionality of your application. In the next couple of days, I will prepare an article about the MVVM Architecture in Android using the Architecture Components and Dagger 2.

Post navigation

About Me

Hello I am Juma Allan, Founder and Author of Android Study. I am currently working as the Lead Android Engineer at dLight Solar, an Open Source Enthusiast and a big time Android Lover, learning Go and sharing my knowledge with others.

“If you don’t build your dream someone will hire you to help build theirs”