A structural guide to MVVM using LIVE DATA + ViewModel + REPOSITORY PATTERN + DI(KOIN) + COROUTINES + ROOM + RETROFIT + Databinding
Lets MVVM for ANDROID | Part 1
A structural guide to MVVM using LIVE DATA + ViewModel + REPOSITORY PATTERN + DI(KOIN) + COROUTINES + ROOM + RETROFIT +…
TL;DR Here is the GitHub repository with complete source code.
A structural guide to MVVM using LiveData, ViewModel, Repository Pattern, KOIN DI, Coroutines, Room, Retrofit, and ViewBinding DataBinding.
Now, before diving deep into the functionality let’s quickly finish some components that were left pending till now. Starting with initialization of the KOIN. Although we have defined all the modules, we still need to initialize the KOIN, and that we will do like below in our MainApplication.kt
and also, let’s have a look at a very simple custom exception class that we have made. We will be handling these exceptions in our MainViewModel.kt.
After that, we will be implementing functionality to the overridden functions in our Repository.kt. Remember from the previous part, we have created an abstract class SafeApiRequestWrapper.kt, for safely wrapping our requests. We will extend our repository to this class too. And hence, finally, it will look like,
The Presentation Layer:
Since all our work has been completed in the data layer lets now move to the presentation layer in which we will create a ViewModel class to call Repository functions and then we will post the response/exceptions onto the view class (MainActivity.kt in our case). We will be injecting an IRepository instance into the MainViewModel.kt constructor.
In the above ViewModel, we have created two functions fetchQuoteFromServer() and addQuoteToDB(), one for fetching quote from remote API and another for saving that quote into the database, and now we will be calling these two functions from our MainActivity.
Coming back to core UI where we try to keep our views as dump as possible as views mustn’t know anything about the data source and should only be concerned with handling UI events and displaying data coming from ViewModels via LiveData.
We will be using data binding, so for that first, we need to enable it in our build.gradle
Using the above function, we can create single liner View Binding as shown below.
Again, you can check out the full explanation over here.
Now, we must initialize our MainViewModel.kt using Koin. It is as simple as an above single liner ViewBinding.
For fetching quotes from the server and saving them into the database, I have added two click listeners in the XML itself.
Since now we have added a new koinViewModels module that means we also need to update it in our MainApplication.kt
Now, after all the steps we finally are ready with a basic MVVM structure that is decoupled, testable, maintainable & scalable too.
Thanks For Reading.