Android Architecture: MVVM with Kotlin, Retrofit, Coroutines, Room and Koin 2021

A detailed summary from Seven Peaks Software

In this article we will be covering Android development, including the best practices of MVVM with Retrofit, Coroutines, Room, Koin, and more.

We will be guiding you through a simple project on Android along with detailed demonstrations and explanations.

Seven Peaks is leading the future of software

View and ViewModel

Model-View-ViewModel is a structural-design-pattern architecture. For example, MVC which is used in web or MVP that was previously used in Android.

How to start a new project

Initialization of the project: let’s start by setting the language to Kotlin and check the “Use androidx libraries” in order to comply with the latest Android trends.

Make application runnable: it will allow us to test our application quickly. So on the left, it’s an empty activity. And on the right, it’s declaring that activity has storing. 

Add ViewModel to the View with Data Binding The ViewModel will only contain an ObservableField which is just a value which can be observed by the view with the observe method. Then, we will set the ViewModel to the view using DataBinding. In the TextView, we can see that its text is set to the message of the view model.

Instantiate ViewModel and set it to the layout using the data binding library. To do that, we have useful classes which are binded by jetpack libraries. So, what we are using right now is ViewModelProviders which is an instance in view model and that uses data binding to hide the binding of the layout.

Coroutines and Retrofit (Model and Retrofit)

Add Retrofit and Coroutines libraries is adding the libraries from the org. We will use lifecycle-viewmodel-ktx. For later, we will use it with consoles. For coroutines, there is one library.

For Retrofit, we have three libraries. First is that main library which allows you to perform requests on the REST API. The second one, converter-moshi which will help us to convert the JSON into one of the models of our application. And, logging-interceptor is just a library which will allow us to have some logs.

Add Models About our models, we have a few articles . Because the application which we have will just display the last articles from the NYT API.

Add Retrofit service Retrofit allows us to request the HTTP method of the API.

What is important here is the suspend in the beginning of the method as  it’s part of coroutines which will take less time to return the results. Since it’s an API core so it may take time. However, if you are using coroutines, you cannot use the suspend function directly in the UI thread. 

Call API From the viewmodel, viewmodel scopes will be in detail which is provided by the lifetime ktx libraries. Then, we will do a launch which we need to do, in order to do a network call on the main thread. 

The main thread is not the same as the retrofit which will not block the UI. And get NYP API service is just a method that returns the service. We can send the message out to be the number of wizards we retreated so far. 

Finally, we get the NYT API service which is in red because it is not really a good practice. For example, if you have 10 models, you don’t have to instantiate every time the retrofit instacing each of them. That is why it is useful to use a dependency injection library. 

Koin

Add koin Library to the build.gradle file of the module.

Add Network Module Now we want to provide our retrofit instance. To do so, we will just add network module value which will not be in any class. It will be a value with a provider method in a dedicated network module. And this will have a single retrofit which means that this dependency will be single terms in order to not create a new instance every time we want to get a retrofit instance. Then, it is using the builder to use the base URL and the converter to validate the converter that can convert JSON to our model.

Also, we can use that instance to get a single term for NYT API service and retrofit instances so we can see how to use another provider. Type of object also needs to be set and then we can create it without an instance of API service.

Start Koin We need to start Koin in the application class. By setting the context that we use in the data analysis which will be the application itself on the list of models. So when they have a network model, we will use that one.

Add MostViewed Module which will be a module to provide a MostViewed model. It is important to notice that Android knows when to instantiate the new model and when it is not needed. And you can use the perverse instance which is made directly by Android. So we can use the view model provider which will use exactly the same scenario for making a new instance or not.

Base Activity is where our activity will extend, just in order to set the modules in the constructor because we have the current modules in the application which we also need to have current models which are dependent on activities.

Back to MostViewedModule we need to load the modules or screen so we can share it in the constructor of the activity. We simply load the modules in the onCreate method of the activity, then the onDestroy, of course, unload it. We are sure that we don’t load too many modules. Moreover, on the bottom right, we have majority which it’s time based activity with a must give module which was created before and a viewmodel.

It has many advantages since our view model does not need to be late for its using binary modality, same as using by legacy and so on. It can be valid, and this will be instantiated only when we need it.

Call API now the NYT API service is an argument of the constructor which also will be the property of the class which we use to get the bust fill out so we won’t need to generate it again.

Room

Add Room Library So the room runtime is the main library. Also, KTX is the library which is needed for room to be able to work with coroutines. Because without a suspend function, we need to use light data. As well as KAPT, is the compiler of the methods.

Add DAO We will add the database access object. As you can see, with the first method which is inserted, we don’t use any SQL at all. There are methods to insert your article and yet for updating an article. One will set an article as read. Another one just for updating the logical one, which we read from the API. This method will update the article if it needs to be updated unlike read methods. 

Add Database Database will be an abstract class with a method to read out DAO classes. 

Why is it an abstract class and not interface?  

It is just to allow us to have some non abstract methods in order to populate class data of our database. 

Add Repository In the new model, we gather data from the viewmodel using NYT API service. However, it is not a good practice because data can come from the network, from the API, sometimes from both of them and so on. It is why we want to separate it to have some classes in which we can use all providers of data such as database instance. Then, in order to get the list of journal articles we use the convert method of the model to turn it into a list of objects. 

Update Module We need to update the module in order to either repository module, which will take the retrofit instance in it. 

Router allows us to move from an activity to another because it is a part which is logic. So, it must be in the viewmodel that actually an android moving from an activity to another one will need the context. In order to get that context, we will need a router class and the module.

Add Router class we will just have a router interface which will open the web view or ViewedArticle. Then, we will implement that interface with another class which will take as an argument activity. With that activity, you can override the openWebView method using the instance of the activity.

Add Module Start by using parameters of activity, so you should set it as an argument and then you will use it to instantiate what you need in activity.

Are you interested in Android development? Get in touch with us below to see how we can help you!

Meet the writers

Gaetan Herfray

Android Tech Lead

Gaetan has been working as a developer since 2007. His first years started as a web developer, helping him become a full-time Android developer since 2011.

Gaetan strongly believes in sharing the knowledge that he has learned in his development career to others, and has been active on various online sites such as StackOverflow and Medium to share his teachings. He has also founded a few meetup groups within his native city in France.

Thida

Digital Marketing Intern

Thida is a Junior Digital Marketing intern at Seven Peaks Software, who is currently working on both content sprouting and article writing. “Working hands-on in marketing has been an amazing experience for me so far. I hope you enjoy reading this article!” says Thida.

Sign up today & start getting tech news.

Get the latest tech trends directly in your inbox each month. And get invited to exclusive events.

    Leave a Reply