Clean Recycler view with MVVM + LiveData + Repository+ DataBinding pattern

MVVM+ LiveData + Repository + Databinding is one of the great architecture pattern to adopt when you are choosing a framework in android. I am really a fan of that architecture. The thing which sometimes irritates is searching down on how to follow that pattern for some of the android’s complex component such as Navigation and recycler view. In this blog post, I am going to cover on how to write a super clean recycler view after adopting MVVM+ LiveData + Repository + Databinding design pattern.

Pre-requisite: Basics of Fragments, Activities, Data-Binding, Live-Data and Navigation in android.

Here’s the link of code base in github repository: ( Suggestion is to pull the repository and then follow the below article to understand what’s happening )

Let’s talk over code 😊

Add all the required implementation for using navigation component and enable data binding-

Step:1) Add Recycler view component in the XML layout of your fragment. Make-sure to enable data binding and create a variable — recyclerViewModel. These variables are to be set from the Fragment file which I have explained further below.

Here, as you can see, I have created a custom attribute for recycler view by using Binding adapter. This attribute will help us to set the adapter and properties for recycler view directly through XML layout. You can find this in ViewBindings.java of this GitHub project repository which I had mentioned above.

Step 2) Create a recycler view item layout. This layout will act as an item in your recycler view which will be populated and shown to the users. Here, position attribute is used only if you want to have a click listener in your item and you can use onclick as like described below-

Step 3) Create a recycler view adapter. Here, as you can you see adapter just expects view model as data and position value. Nothing else is required. Everything else is stored in ViewModel. This is one of the expected clean design of adapter when we adopt MVVM pattern.

Step 4) In the view model, call the repository and load the data items. Once you do that, call notifydatasetchanged() over the adapter instance and that will update recycler view contents.

Step 5) Set the recycler view model from the JAVA class file of the fragment:

That’s all. You are done.


Next up coming article — Using LiveData efficiently in MVVM design pattern