Free Live Coronavirus Cases API With LiveData and MVVM

We’re going to implement live Coronavirus cases Apis with LiveData & MVVM

Himanshu Verma
Towards Data Science

--

Photo by Dương Trần Quốc on Unsplash

What we will build?

We’ll build an Android Application which will show the live cases of Coronavirus in RecyclerView. We’ll follow the MVVM Architecture Pattern, and implement LiveData with Kotlin.

Our final application will something like this.

What we’ll learn?

  • MVVM Architecture Pattern
  • LiveData
  • Using Retrofit APIs

Why MVVM?

MVVM is an architecture design pattern which helps us to achieve the following things.

  • MVVM makes code more understandable
  • Code becomes easier to maintain for other developers
  • It also makes the project loosely coupled meaning reduces the dependencies between the components such as classes, activities and fragments.
  • Code testing becomes a lot more easier.

MVVM Architecture Pattern

MVVM Architeture

In the diagram shown above explains the MVVM architecture pattern. In this diagram, there exists our views at top of the architecture through which users interact with data.

To display data, we use ViewModel, so our views are dependent on ViewModel to get the data. The benefit of using ViewModel is, it will not update the data, if the activity is destroyed. This means that it reduces the chances of app crashing.

Next, there exists Repository below the ViewModel, which is further dependent on various data sources. A repository can get the data from any sources, it may be a remote repository or local repository, it totally depends upon your logic.

LiveData

When it comes to observable or observer, then this means that we’re talking about two different things, one you can think of as T.V. and the other you can think of a person who is watching it. So T.V. is the observable since it is being observed and the person watching it, is an observer. And if we apply this concept on our data and views, data is being observed by our views, so data is the observable and views are the observer. Now I hope you could be able to understand the concept.

Now its time to be a little technical, isn’t it?

LiveData is an observable data holder class which means that the class which extends the LiveData class is responsible for notifying the views that are in active state. As soon as any change occurs in the data, it becomes visible to our views i.e our views are notified.

Let’s consider a scenario to better understand the concept.

Ex:-

Let’s suppose, you’re on the home screen of any app and it is showing you list of items but as soon as you click on the any of the items, then some processing occurs which means data is being fetched by the background service and at the same time, you close the application. And the app is not visible to you but background service stops soon (Since you closed the app), and it is still trying to set the data on the views, now since the data isn’t fetched, so your app will be crashed in the background because of NullPointerException. That is the problem of not using the LiveData.

Now we can understand from this example is that our process of fetching data is not aware of the life-cycle of our activities, fragments and services, that’s why our app crashes.

The only solution available in the market is the LiveData which solves such problems. So what we’re waiting for? let’s dive directly in the coding part.

Project Structure

Create the following packages in your project

network package:

This package contains two more packages i.e data and repos, data package has two classes to receive the data fetched from the RemoteRepository class.

ui package:

This package also has two more packages, and they are adapters and interfaces, adapters package has a ModelListAdapter class and this class creates a list of details of Coronavirus.

interfaces package contains an interface which returns the Retrofit object. In this interface, I defined the BASEURL and its ENDPOINT.

The next two classes of ui package is MainActivity and MyViewModel. Our MainActivity class contains the RecyclerView and ProgressBar. And MyViewModel class provides the data to our activity.

Enough talking, Let’s start coding now…

I’m going to use FREE coronavirus api for this project.

API URL: https://api.covid19api.com/summary

I’ll only use Countries array.

MainActivity.kt

I have a single screen in this application, and this screen portrays a list of Coronavirus details using RecyclerView.

ViewModelProviders is a class and of() method of this class returns the object of our MyViewModel class for the scope of activity. This is the main class which provides the core logic of ViewModel. Once we created the object of our MyViewModel class, now we can start observing the data using the observer() method. This observer takes two parameters i.e current activity’s context and Observer anonymous class. An anonymous class is an unique class which doesn’t have any name and these classes reduce number of class .java files, these classes are used for some specific situations, when there is only one time use is necessary. Inside the Observer anonymous class, we’re setting our recyclerview adapter to display our list of items. So that’s the only code we needed in our activity. As observer() sees any update in the data, it notifies the adapter or any views.

The layout file of MainActivity contains only recyclerview and a progressBar to show processing while data is being fetched from the remote repository.

ModelListAdapter.kt

This is adapter class which sets the item list in the recyclerview. This class is called from the MainActivity. ModelListAdapter class uses list_item layout file which has four textviews to display the data.

Layout file of our adapter class.

MyViewModel.kt

This is our ViewModel class and the MainActivity.kt class is dependent on this class. Whenever views needed data, this class provides it. The ViewModel class is only responsible for managing the data. This class can never access the views. The callAPI() method of this class accesses the object of Repository class and calls its callAPI() method. Then Repository class returns the object of MutableLiveData object. This object further passes to the our MainActivity to set the data.

RetrofitApiService

It is an interface that has fetchData() method, and this function returns the object of Country class. Notice that fetchData() method is annotated with @GET request which means the we’re going to make is a GET request. Get request is used only when data is only being fetched from the server meaning neither data is being sent nor being updated on the server, inside the Apart from this, this interface also creates the singleton object of Retrofit class. invoke() function is inside the companion object, this means that whenever we need to call this invoke() method, we’ll not have to create the object. companion object is same as Java’s static method. In the baseurl() method, i passed the url of my webserice.

Repository.kt

Repository class handles the network calls. When callAPI() method of this class is called from the MyModelView class, soon it starts executing its asynchronous method enqueue(). This method has two callbacks, onFailure() and onResponse(), if call is successful, the onResponse() is called otherwise onFailure() is called.

Data classes:

Country is my main class which takes a list of GlobalData class in the constructor. This class is returned by our API.

class Country(val Countries: List<GlobalData>) {

}

And this is the data that we are getting from the API.

data class GlobalData(
var Country: String,
var NewConfirmed: Int,
var TotalConfirmed: Int,
var NewDeaths: Int,
var TotalDeaths: Int,
var NewRecovered: Int,
var TotalRecovered: Int
)

The advantages of using LiveData

  • Ensures your UI matches your data state
  • No memory leaks: Observers are bound to Lifecycle objects and clean up after themselves when their associated lifecycle is destroyed.
  • No crashes due to stopped activities: If the observer’s lifecycle is inactive, such as in the case of an activity in the back stack, then it doesn’t receive any LiveData events.
  • No more manual lifecycle handling: UI components just observe relevant data and don’t stop or resume observation. LiveData automatically manages all of this since it’s aware of the relevant lifecycle status changes while observing.
  • Always up to date data: If a lifecycle becomes inactive, it receives the latest data upon becoming active again. For example, an activity that was in the background receives the latest data right after it returns to the foreground.
  • Proper configuration changes: If an activity or fragment is recreated due to a configuration change, like device rotation, it immediately receives the latest available data.

If you stuck somewhere in the code, then don’t worry you can download my Github project from HERE.

I hope you liked reading this article, you can also visit my website where I keep posting article regularly.

Subscribe my mailing list to get the early access of my articles directly in your inbox and Don’t forget to follow my own publication on Medium The Code Monster to polish your technical knowledge.

Conclusion

We have seen how LiveData can be used with MVVM and Retrofit APIs. And to elaborate the use case of LiveData, i used Live Api, so that it helps you to understand the LiveData concept easily.

--

--

Visit my website http://thehimanshuverma.com/. Android & IOS Developer | Researcher | ML & Data Science Enthusiastic | Blogger | FA