Android ViewModel using Retrofit – ✅ A Simple Tutorial

Heard about ViewModel in android? Android ViewModel is an architecture component that is designed to store UI related data. According to Android Developer Website.

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.

If you remember one of our last Retrofit Tutorial where we learned about fetching JSON data from a URL. Now if one of our activity has some data on it fetched from server, but if for some reasons (for example orientation changes) the activity is recreated it will fetch the data from the server again. Fetching the same data from the server is a waste of resources. An efficient solution here is to separate the view data ownership from UI Controller logic.

So, in this Android View Model tutorial we will do the same thing we did in the previous Retrofit Tutorial but here we will be using the ViewModel architecture.

Setting Up Android Project with RecyclerView and Retrofit

Creating a new Android Studio Project

  • As always the first step is creating a new Android Studio Project. And in that project we will see how to work with Android ViewModel.
  • I have created a project using an EmptyActivity named AndroidViewModel.

API to fetch data

  • You can use any URL if you have any, to fetch data. Here I am going to use the following URL.

https://www.simplifiedcoding.net/demos/marvel/

  • The above URL is returning a list of Marvel Super Heroes. You can open the URL to see what it is returning. It is the same URL that we used while learning Retrofit JSON.

Adding Required Dependency

For this project we are going to use the following dependencies.

  • RecyclerView – To display list of superheroes.
  • Glide – To load image from URL.
  • Retrofit – For fetching data from the URL.
  • ViewModel – The architectural component

So the first we will add all the above mentioned dependencies in the app level build.gradle file.

After adding all the dependencies sync your project.

Creating the POJO class for Hero

  • Create a new class named Hero.java and write the following code.

Setting Up RecyclerView

Creating RecyclerView and RecyclerView Layout

  • Now come inside activity_main.xml and create a RecyclerView here, in this RecyclerView we will display the Hero List.

  • Now we will also create one more layout resource file for the RecyclerView.
  • Create a layout resource file named recyclerview_layout.xml and write the following xml code.

Creating RecyclerView Adapter

  • Now we need the RecyclerView Adapter. We are going to use the below code for this. If you are not sure what it is all about, you can check the RecyclerView Tutorial.
  • So just create a new class named HeroesAdapter.java and write the following code.

Setting Up RecyclerView

  • Now come back to MainActivity.java and write the following codes.

  • Now we will setup the Retrofit to fetch data from URL.

Setting Up Retrofit

The API Interface

  • Create a new interface Api.java.

  • Till here we done the things that we have already learned in the previous tutorials. Now we will use ViewModel architecture to load the data in RecyclerView.

Using Android ViewModel to load data Asynchronously using Retrofit

Creating Android ViewModel

  • For creating a ViewModel, we need to create a class that will extend the ViewModel class.
  • Here I am creating a class named HeroViewModel.java.

  • The fetch using Retrofit part is exactly the same here that we already learned in the Retrofit Tutorial.
  • And the ViewModel thing is very easy, we only have a method named getHeroes(). Inside this method we are checking if the List is null then we will get it asynchronously. Remember we need to use MutableLiveData and LiveData classes for storing the List and the rest is managed by the ViewModel component. So you do not need to worry about other things.

Using the Android ViewModel for Displaying the Hero List

  • Write the following code at the end of onCreate() method in MainActivity.java.

  • Now you can run your application, to check if it is working or not.
Android ViewModel Tutorial
Android ViewModel Tutorial

As you can see it is working fine. The advantage of doing this way is, if our activity recreates then it will not fetch the data again making our application more efficient. And yes you can get my source code from the below given GitHub repository.

Android ViewModel Example Source Code

I hope you found this tutorial helpful. If you are having any confusion regarding this Android ViewModel tutorial then leave your comments. And please don’t forget to SHARE this post with your friends. Thank You.

 

24 thoughts on “Android ViewModel using Retrofit – ✅ A Simple Tutorial”

  1. I’m a selftaught and a beginner to programing from central Africa.

    I want a kotlin code with one editText with an onfocuschange listener. Onfocuschange it should it should square the input.

    I have tried alot to search online but it is not available ( best of my search)

    Reply
  2. I tried the code and I have a question that when I keep rotating the screen then onChanged is keep getting called, is this expected???

    Reply
    • As you know, any View Models associated with an Activity or Fragment are designed specifically to persist across configuration changes, effectively providing caching for the data they store. We should use observe method to add an Observer implementation whose onChanged handler will be triggered whenever the underlying data changes. Because your View Model lifecycle is based on your application—rather than the parent Activity or
      Fragment—the View Model’s Live Data’s loading function won’t be interrupted by a device configuration change.
      Similarly, your results are implicitly cached across device configuration changes. After a rotation,
      when observe is called on the View Model’s data, it will immediately return the last result set via
      the onChanged handler—without the View Model’s loadData method (loadHeroes() in Belal khan tutorial) being called. This saves signifcant time and battery power by eliminating duplicative network downloads and the associated processing. I hope this would be helpful.

      Reply
  3. Hello Belal Khan!
    Thankyou for yr awesome tutoriels!
    I have this problem i use retrofit(for the remote backend) for send image to the php server uploaded from the camera!
    The type of the image is byte in my POJO class and in my server i have the filename!
    What i should do ?
    Thanks!

    Reply
  4. HeroesViewModel model = ViewModelProviders.of(this).get(HeroesViewModel.class);

    I’m getting an error in(.of) . Help me to resolve this, i have the dependencies also

    Reply
  5. Can you please show how to implement this with repository as you are getting the data from ViewModel itself which should come from a repository as per the workflow provided by Google. I see the repository part missing here Thanking you in advance.

    Reply
  6. kindly explain this how you can call ViewModelProviders.of(this).get(HeroesViewModel.class);
    are you use an androidx library for that…or what ?

    Reply
  7. loadheroes() executes asynchronously, that means return might call before getting data from webservice and in that case herolist will be null. How to solve this issue??

    Reply
  8. unable to to download code. its not getting downloaded even when i subscribed your youtube channel. wondering if you know this issue

    Reply
    • Click the download link,
      You will see the download page where link is locked, now follow these steps
      #1 Click on Subscribe Button, it will open a new tab, in this tab subscribe if you are not already subscribed. If you are already subscribed ignore this tab and go back to the download page. Make sure you don’t open the download page again and go back to the already opened page.
      #2 Wait for few seconds and the download link will unlock.

      Reply

Leave a Comment