Getting Started with Android Architecture Components

The Android Architecture Component library was introduces in Google I/O 2017 which is now available in Stable Version.So i thought it is the right time to starts with this components and I recommend you to starts using in your apps too

What are Architecture Components?

Architecture Components is a collection of libraries that help you design robust, testable, and maintainable apps. Start with classes for managing your UI component lifecycle and handling data persistence.

In simple words, this library helps us to better handle the persisting of data across Life-Cycle events and configuration changes, whilst also helping us to create a better architecture application and avoid boiler plate classes that are difficult to maintain and test.

Why Architecture Components?

Unlike others traditional desktop counterparts which, in the majority of cases, have a single entry point from the launcher shortcut and run as a single monolithic process, Android apps have a much more complex structure. A typical Android app is constructed out of multiple app components, including activities, fragments, services, content providers and broadcast receivers.

The problems faced by many Android Developers while developing is to follow a Standard Architecture Pattern which resolved their common problems like LifeCycle issue,UI updates from local data or from the networks and yeah!! how can i forgot the configuration changes when the devices is rotated I know every one have faced this issues.And android:screenOrientation="portrait" is not the real solution :P

So to overcome this problem and to provide a standard guidelines for architecture pattern they have introduced four components

  1. LifeCycle : Lifecycle-aware components perform actions in response to a change in the lifecycle status of another component, such as activities and fragments
  2. LiveData : LiveData is lifecycle-aware component,This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.
  3. ViewModel : The ViewModel class is designed store and manage UI-related data so that data survives the configuration changes such as screen rotations
  4. Room : Room is a robust SQL Object Mapping Library for Data Persistent
Note: It is impossible to have one way of writing apps that will be the best for every scenario. That being said, this recommended architecture should be a good starting point for most use cases. If you already have a good way of writing Android apps, you don’t need to change.

Let’s start at the top and take a journey through what each of these components’s responsibility and how to implemented in our app

LifeCycle

As per the documentation, Lifecycle is an abstract class which has an Android Lifecycle attached to it — and, because it is holding this state of the lifecycle, objects can observe this state and react accordingly. In order to keep a track of this state, there are two fundamental concepts that the Lifecycle class incorporates i.e Events and State represented in the below diagram

Event

An event is the lifecycle event that has been trigger by a lifecycle change (such as resuming/pausing an activity). We can implement this LifecycleObserverand get callbacks using Annotation provided in arch.lifecycle package to handle lifecycle changes.Below is sample code snippet for it

NOTE:
ON_CREATE , ON_RESUME , ON_START
This will all be called after the LifeCycleOwner(i.e Activity/Fragment) corresponding method has returned
ON_DESTROY , ON_PAUSE , ON_STOP
This will be call before the LifeCycleOwner (i.e Activity/Fragment) corresponding method has been called

State

In simple words the current state of the component tracked by the Lifecycle object is the State of that object.Following are the state in LifeCycle object and you can also get this state by manually calling getCurrentState() in LifeCycle Object

  • CREATED — The state of the lifecycle after the ON_CREATE event but before the ON_START event. It is also in this state after the ON_STOP event and before ON_DESTROY.
  • DESTROYED — The state of the lifecycle after the ON_DESTROY event.
  • INITIALISED — The state of the lifecycle at the initial starting point.
  • RESUMED — The state of the lifecycle after the ON_RESUME event.
  • STARTED — The state of the lifecycle after the ON_START and before the ON_RESUME event. It is also in this state after the ON_PAUSE event and before ON_STOP.

LifecycleOwner

In order to work the LifeCycleObserver mention above it should attached to a to a class which implements LifeCycleOwner (Activity/Fragments)
As we know that the Architecture components are in stable version so by default Activity/Fragments implements the LifeCycleOwner so we don’t require to implement LifeCycleOwner in Activity/Fragment

You can the add LifeCycleObserver to LifeCycleOwner like this

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
        //This is how you add LifeCycleObserver
getLifecycle().addObserver(new MyLifeCycleObserver());
}

If you are still using the unstable version than follow this LINK

Note: For LifeCycleOwner stable version you need to use support libraries 26.1.0 and 1.0.0 for lifecycle components LINK

Now that we’ve got a better understanding of how the Lifecycle and its components work, Now its time to understand how to handle the configuration changes better in our app. For that we going to use ViewModel component

ViewModel

The ViewModel class is designed store and manage UI-related data so that data survives the configuration changes such as screen rotations.This means that our activity or fragment no longer needs to have the added responsibility of retaining this state as the ViewModel takes on this responsibility. All the hard work is done for us 😁

The ViewModel life cycle provide only one method which is onCleared() that will be automatically called to clear up the ViewModel before Activity/Fragment get destroyed

ViewModel LifeCycle

So here we are going to work on just a simple example which will show the number of time the devices is rotated by using ViewModel. The reason behind this example is to demonstrate the object is saved and retained in ViewModel when the activity is recreated

You can create a ViewModel class by extending to ViewModel. Here we will define a rotation count which will increments its value when ever its called and save and retained the mRotationCount value

public class MyViewModel extends ViewModel {
    private int mRotationCount = 0;

public int getRotationCount() {
mRotationCount = mRotationCount + 1;
return mRotationCount;
}
}

In some cases if you want context to get system service or some other stuff you can use AndroidViewModel instead of ViewModel which will provide you application context

public class MyViewModel extends AndroidViewModel {
private int mRotationCount = 0;
private Context mContext;

public MyViewModel(@NonNull Application application) {
super(application);
mContext = application.getApplicationContext();
}


public int getRotationCount() {
mRotationCount = mRotationCount + 1;
return mRotationCount;
}
}

Hence we dont require context we will use a ViewModel class. Now we understand a little more about what a ViewModel is, we need to be able to fetch the ViewModel instances with our activity/fragment. For this, we have access to a helper class known as ViewModelProviders — in our activity/fragment, this would look something like this and set the TextView to rotation count like this

So every time the devices is rotated and activity is recreated onCreate() will be called.So here is the ViewModel magic happens,The ViewModel will save and retained the value and whenever the getRotationCount() method is called it will provide the latest incremented value

Caution: 
A ViewModel must never reference a view, Lifecycle, or any class that may hold a reference to the activity context.

LiveData

The LiveData component is a data holder that contains a value that can be observed. LiveData will behave according to Lifecycle state.This class provides us with the ability to hold a piece of given data and also observe it across lifecycle changes.It notifies the observers when data changes so that you can update the UI.

LiveData can be customize because there's a lot of difference situations which LiveData can be alter the way in which decides when / if data is emitted.in

LiveData Observe LifeCycle

To get a better understanding of all these different situations, let’s walk through this step-by-step

Create LiveData Object

public class NameViewModel extends ViewModel {

// Create a LiveData with a String
private MutableLiveData<String> mCurrentName;

public MutableLiveData<String> getCurrentName() {
if (mCurrentName == null) {
mCurrentName = new MutableLiveData<String>();
}
return mCurrentName;
}
}

Here we have create Mutable LiveData String so that we can change the value of Current Name

Observe LiveData objects

Here as per the above code When we call observe() there are a few different cases that can occur. First of all, if the LifecycleOwner is in the DESTROYED state then this call will be completely ignored. However, if it’s not DESTROYED then at this point the observer is added to the list of observers which is retained by the LiveData class. — this means that if Lifecycle reaches DESTROYED, then the observer will automatically be removed — meaning we can easily avoid memory leaks from these situations.

Update LiveData objects

mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String anotherName = "John Doe";
mModel.getCurrentName().setValue(anotherName);
}
});

When we call setValue(anotherName) the value of the live data will be set. At this point, if there are active observers for our MutableLiveData<String> class AND the Lifecycle of our LifecycleOwner is in an ACTIVE state, then the value will be emitted to those observers and respective UI will be updated.We can setValue() only in MutableLiveData<T> class

Conclusion:

I think this components will save a lot of trouble for specially managing the life cycle process in the Activity/Fragment.The best part of this components is you can use each component individually as per your need in the project.Each components works independently.But it will benefit you more if you use them together

I’ve create a sample project to demonstrate the implementation of this components all together

If you liked this, click the 💚 below so other people will see this here on Medium. If you have any quires or suggestions, feel free to hit me on Twitter.

Credits:

  1. Android Architecture Components : http://bit.ly/2yV2TIM
  2. Exploring Android Architecture Components: http://bit.ly/2hKrjS5
  3. Introduction to Android Architecture Components : http://bit.ly/2yXxm8T

Thank you

PS: Please stay tuned for my new blog on Room Persistence library

Like what you read? Give Burhanuddin Rashid a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.