Playing with Android Architecture Components + Retrofit — Part 1

Álvaro Blanco Cabrero
4 min readMay 23, 2017

Google recently announced its new architecture based set of libraries at I/O 2017 under the name of Android Architecture Components. This libraries greatly simplify our lives when dealing with Android’s lifecycle, delegating its management to them.

To demonstrate how this new libraries can make our app more robust and maintainable I will write an example showing the core classes of a simple app I made to test this new components.

The app fetches a list of organizations from Github API using Retrofit as networking library, so we will start creating the data layer

Data Layer

First we start creating the interface to define Retrofit’s method call (https://api.github.com/organizations)

We need to define the organization model to. We will use a Kotlin data class to accomplish it:

Also a class to call our defined Retrofit service

Now we are going to create our entry point to access Github service. It will be a singleton:

Now we can simply access our service and make the call to organizations API, but we are going to make our app a little bit smarter integrating Android Architecture Components.

You can add them from Google’s Maven

repositories {
maven { url 'https://maven.google.com' }
}
compile 'android.arch.lifecycle:runtime:1.0.0-alpha1'
compile 'android.arch.lifecycle:extensions:1.0.0-alpha1'
annotationProcessor "android.arch.lifecycle:compiler:1.0.0-alpha1"

Let’s take a look to one of them:

LiveData

From Android Developer page: LiveData is a data holder class which keeps a value and allows this value to be observed. Unlike a regular observable, LiveDatarespects the lifecycle of app components, such that the Observer can specify a Lifecycle in which it should observe.

LiveData considers an Observer to be in active state if the Observer’s Lifecycle is in STARTED or RESUMED state.

Using this class we can forget the lifecycle management by delegating to it and ensuring that our observer will only be called in an active state.

Let’s create an extension of this class to hold our data

Network status exposure is omitted for the sake of clarity

onActive method is automatically called when the first observer is added (when observers change from 0 to 1), so this is the ideal method to start calling Github API.

LiveData also has an onInActive that is called when there are no remaining observers, but we are not going to implement it because we will rely on another class called ViewModel to do the proper cleaning/canceling.

Once we get the response, we set the value property (from getValue()/setValue in java) to let LiveData to notify our active observers.

Note that we are only executing the call when the first observer is added. This is because LiveData always calls a new observer with the last data it has, so subsequents observers will always receive the API response (also we could not reuse the same call object unless cloned :D ).

Also we will need to modify our OrganizationHandler class to return this new type of data

Now we can simply observe this LiveData to start calling and we will receive the response in a callback.

DataHandler.INSTANCE.organizationHandler
.getOrganizations()
.observe(this, Observer { response -> })

Note: observe method from LiveData needs an instance of LifeCycleOwner, a class that have an Android lifecycle. Every class can implement this interface an provide the lifecycle, but we can use two already built classes: LifecycleActivity and LifecycleFragment

This approach is totally ok, as we are getting automatically unsubscribed after onPause() callback and we are getting notified with the last value on subsequents subscribes during the LifeCycleOwner scope. But what happens if the user decides to rotate the device? Nothing good: Activity will be recreated and a new instance of our RetrofitLiveData with it, making the call again. One solution is to keep and static instance of our RetrofitLiveData out of the Activity scope and everything will be ok, because our observers will be automagically removed when the Activity is destroyed, avoiding memory leaks but there is no need to do this, because again Android Architecture Components are here to save our lives.

ViewModel

ViewModel is designed with the separation of concerns principle in mind. It’s a class that allows as to separate UI work from business logic. It is retained during configuration changes so it outlives the activity.

To gather an instance of a ViewModel for an Activity or Fragment, we should call

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

If the activity is re-created, it receives the same MyViewModel instance that was created by the previous activity. When the owner activity is finished, the Framework calls ViewModel’s onCleared() method so that it can clean up resources.

Now let’s create our custom ViewModel:

That’s all! Now in our Activity we simply need to access the ViewModel and make the call

ViewModelProviders.of(this)
.get(OrganizationListViewModel::class.java)
.liveData.observe(this, Observer { response ->})

The first time we observe the LiveData the call will be started and subsequent times we are only going to receive the cached result also surviving configuration changes and making the call once during the Activity lifecycle.

In Part 2 I will add persistence with Room, so stay tuned!(https://developer.android.com/topic/libraries/architecture/room.html).

If you find this post useful, click the💚 below so other people can see it too!

--

--