LiveData was created as a lifecycle-aware data holder with the observer

pattern in mind. So basically when data changes it will automatically notify the views and change it. When we create a LiveData object then our views, either an Activity or Fragment will act as an observer to this data then update but still respecting lifecycle states. With LiveData we can write code for observing these data changes and update views accordingly.

The advantages of using LiveData as revealed here:

- Ensures your UI matches your data state

- No memory leaks

- No crashes due to stopped activities

- No more manual lifecycle handling

- Always up to date data

- Proper configuration changes

- Sharing resources

___________________________________________________________________

Let’s start getting into a thorough understanding of LiveData, ViewModel, MutableLiveData and Coroutines with a simple demo project in Kotlin.

We’ll use Retrofit2 for Rest API calling which will fetch data from a server and display it on RecyclerView with the help of ViewModel and LiveData.

The following components will be demonstrated in this sample application.

LiveData

MutableLiveData

ViewModel

Retrofit2

Moshi

Coroutines Networking

Glide

Create a new project:

Create a new project in Android Studio with the EmptyActivity template and name it LiveDataExample. Now add these dependencies into the app/build.gradle file.

MVVM diagram

Create your package/folder MVVM architecture:

We’re creating a MVVM architecture so create your folder structure as follows model, view, viewmodel and networking for our REST API interface.

Architecture

Create your models:

We’ll create two data models to match up to our endpoint, namely Blog and BlogWrapper. Pop these into your model folder package:

Create the Rest API interface service:

Setup your Retrofit2 instance with your Coroutine endpoint all in one (for simplicity).

We’ve added a timeout with a okHttp client and also notice the Moshi converter. :)

Once this is created pop it into your networking package folder.

Create a repository for LiveData interaction:

Put this in your viewmodel package folder.

Create your viewmodel:

Our viewmodel initializes our BlogRepository and retrieves our blog data with our getter.

Let’s go now and create all the UI we require:

We’ll create blog_item and activity_main.xml.

Add our BlogAdapter:

And Finally our MainActivity:

Let’s pull our whole app together now.

As you can see LiveData and MutableData handle the way the data is displayed to the UI and updates reactively and is a much better way to handle API data than before.

I hope you enjoyed this tutorial and gained a better understanding of Google’s architecture components.

You may view and download the final completed project here.

Happy coding! :)