Android modularization, part 3
Part three of this Android modularization series introduces the presentation module and shows how to organize a feature and its dependencies.

Editorial translation by Impulso.
MVVM, Koin, Rx, Room, Data Binding, and a little more…
In the first two articles, we covered the domain and data modules.
- Domain
- Data
- Presentation
Presentation Module
We’ve finally reached the last module in our project! For our users, it’s the most important one, because this is where we’ll display our data in the app.
What’s in the presentation module:
- View: these are our Activities/Fragments, where we’ll display our data.
- ViewModel: this is where we’ll manage the data for our Views, for example by calling our repository to consume or observe data.
Flow diagram for the presentation module:

Our view requests the list of jobs from the ViewModel, which uses the repository to fetch the data to display.
When we first created our project, it came with an app module, and that’s what we’ll use as our presentation module.
Let’s start building the Presentation module:
The first thing we’ll do is add the dependencies we need to our dependencies.gradle file for the presentation module.
We’ll add Koin ViewModels, so we can inject our ViewModels, as well as Data Binding and ViewModel. The rest is mostly routine development work, but if you have any questions, I’m happy to try to help.
ext {
//Android Config
minSDK = 20
targetSDK = 28
compileSDK = 28
buildTools = '3.4.0-beta04'
appCompactVersion = '1.0.2'
kotlinVersion = '1.3.21'
AndroidArchVersion = '1.1.1'
databindingVersion = '3.1.4'
lifeCycleVersion = '2.0.0'
ktxVersion = '1.0.1'
constrainVersion = '1.1.3'
cardViewVersion = '1.0.0'
recyclerViewVersion = '1.0.0'
//Rx
rxJavaVersion = '2.2.7'
rxKotlinVersion = '2.2.0'
rxAndroidVersion = '2.1.1'
//Koin
koinVersion = '2.0.0-rc-1'
//Retrofit
retrofitVersion = '2.3.0'
//Gson
gsonVersion = '2.8.5'
//Room version
roomVersion = '2.1.0-alpha06'
//Test
junitVersion = '4.12'
espressoVersion = '3.1.1'
runnerVersion = '1.1.1'
dependencies = [
kotlin: "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion",
appCompact: "androidx.appcompat:appcompat:$appCompactVersion",
constraintlayout: "androidx.constraintlayout:constraintlayout:$constrainVersion",
cardView: "androidx.cardview:cardview:$cardViewVersion",
recyclerView: "androidx.recyclerview:recyclerview:$recyclerViewVersion",
viewModel: "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifeCycleVersion",
lifeCycle: "android.arch.lifecycle:extensions:$AndroidArchVersion",
dataBinding: "com.android.databinding:compiler:$databindingVersion",
ktx: "androidx.core:core-ktx:$ktxVersion",
rxJava: "io.reactivex.rxjava2:rxjava:$rxJavaVersion",
rxKotlin: "io.reactivex.rxjava2:rxkotlin:$rxKotlinVersion",
rxAndroid: "io.reactivex.rxjava2:rxandroid:$rxAndroidVersion",
koin: "org.koin:koin-android:$koinVersion",
koinViewModel: "org.koin:koin-androidx-viewmodel:$koinVersion",
retrofit: "com.squareup.retrofit2:retrofit:$retrofitVersion",
retrofitRxAdapter: "com.squareup.retrofit2:adapter-rxjava2:$retrofitVersion",
retrofitGsonConverter: "com.squareup.retrofit2:converter-gson:$retrofitVersion",
gson: "com.google.code.gson:gson:$gsonVersion",
room: "androidx.room:room-runtime:$roomVersion",
roomRxJava: "androidx.room:room-rxjava2:$roomVersion",
roomCompiler: "androidx.room:room-compiler:$roomVersion"
]
Now let’s add our libraries to the Gradle file for the presentation module:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.mymoduleexample"
minSdkVersion 20
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
dataBinding {
enabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation project(path: ':domain')
implementation project(path: ':data')
def dependencies = rootProject.ext.dependencies
def testDependencies = rootProject.ext.testDependecies
implementation dependencies.appCompact
implementation dependencies.constraintlayout
testImplementation testDependencies.junit
androidTestImplementation testDependencies.runner
androidTestImplementation testDependencies.espresso
implementation dependencies.cardView
implementation dependencies.recyclerView
implementation dependencies.kotlin
implementation dependencies.ktx
implementation dependencies.viewModel
implementation dependencies.lifeCycle
implementation dependencies.koin
implementation dependencies.koinViewModel
implementation dependencies.rxJava
implementation dependencies.rxKotlin
implementation dependencies.rxAndroid
kapt dependencies.dataBinding
To use Data Binding, we need to add:
dataBinding { enable true}
Our module needs the other modules to work. That’s why we add them as implementation dependencies here.
I added a new variable called testDependencies just to organize our test dependencies. We aren’t writing tests in this tutorial, though.
Here, we’ll go through each package, what it’s for, and what it contains:
Extensions: this is where we keep the extensions we can use in our module, and in this case we have 3 classes**.**
- Context extensions: a set of extensions for the Android context. We only have one here, to show a toast, and to use it inside an activity, for example**,** all we need to do is call toast(MENSAGEM). If you want to add another extension for the context, just add the method to this class (the same goes for the next two).
inline fun Context.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, message, duration).show()
}
- View extensions: a set of extensions for views. Here we have visible, which changes the visibility of a view. To use it, just call, for example, txtName.visible(true).
fun View.visible(visible: Boolean = false) {
visibility = if (visible) View.VISIBLE else View.GONE
}
- ViewGroup extensions: a set of extensions for ViewGroup. Here we have inflate, which is extremely useful in adapters. One example is parent.inflate(R.layout.item_android_job), which we use in our AndroidJobsAdapter (you can check it out further down).
fun ViewGroup.inflate(layoutId: Int, attachToRoot: Boolean = false): View {
return LayoutInflater.from(context).inflate(layoutId, this, attachToRoot)
}
- ViewModel: here we have our BaseViewModel, which all our ViewModel classes will extend. We also have our StateMachine, which manages the states of our repository calls inside the ViewModel.
- BaseViewModel: it simply extends the ViewModel class and holds our disposables, which manage the lifecycle of the Observables from our useCase calls (these are of type Single, but they could be Observables).
open class BaseViewModel: ViewModel() {
val disposables = CompositeDisposable()
override fun onCleared() {
disposables.clear()
In onCleared(), which is called when the ViewModel is destroyed, we clear all the Observables stored in our disposables. This matters because if we don’t dispose of the observables, they can keep running and cause a memory leak. We use CompositeDisposable(), which is just a container for disposables.
- ViewState: a state manager that lets us show the right state in the view, depending on what’s emitted**.**
sealed class ViewState<out T> {
object Loading : ViewState<Nothing>()
data class Success<T>(val data: T) : ViewState<T>()
data class Failed(val throwable: Throwable) : ViewState<Nothing>()
}
class StateMachineSingle<T>: SingleTransformer<T, ViewState<T>> {
override fun apply(upstream: Single<T>): SingleSource<ViewState<T>> {
return upstream
.map {
ViewState.Success(it) as ViewState<T>
}
.onErrorReturn {
ViewState.Failed(it)
}
.doOnSubscribe {
First, there are 3 possible states:
- Loading: this state is emitted in .doOnSubscribe, because we want to show the loader as soon as our stream starts. No data is needed to emit this state, since we use ViewState to create it.
- Success: this state is emitted in .map, which applies a specific operation to the emitted item. In this case, it emits Success along with the data from the stream (our list of jobs).
- Failed: when something goes wrong in our stream, Failed is emitted in onErrorReturn along with the emitted throwable (error).
StateMachineSingle: we’ll apply it to our Single calls from the repository so it can emit the states we mentioned above.
Now that we’ve covered each part of the stream, let’s move on. We’ll see how it works in more detail later, but for now I recommend this interesting video that explains what we did in detail.
Feature
We use this naming convention for each feature, and in our case we have two features/packages: list and main.
- Main: this screen is just there to give us a way to navigate to our list, but let’s see how it works:
MainViewModel: this is where we handle the data we’ll use in our view.
class MainViewModel: BaseViewModel() {
val showAndroidJobsLiveData = MutableLiveData<Boolean>()
val outAppLiveData = MutableLiveData<Boolean>()
fun onShowAndroidJobsRequire() {
showAndroidJobsLiveData.postValue(true)
}
As you can see, we have 2 LiveData objects whose values we update in the onShowAndroidJobsRequire and onOutAppRequire methods, which are called from the XML. To make this possible, we use Data Binding.
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<import type="android.view.View"/>
<variable
name="viewModel"
type="com.example.mymoduleexample.feature.main.MainViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".feature.main.MainActivity">
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btnShowList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="@string/show_list"
android:onClick="@{() -> viewModel.onShowAndroidJobsRequire()}"
app:layout_constraintBottom_toTopOf="@+id/btnOut"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.501"/>
<TextView
android:id="@+id/btnOut"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:text="@string/out"
android:gravity="center"
android:onClick="@{() -> viewModel.onOutAppLiveData()}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btnShowList"/>
This is the layout for our view. Now let’s explain how we bind it to our ViewModel using Data Binding.
To use our MainViewModel in our layout, we first need to wrap the entire layout in a layout block.
Next, we create a data block where we’ll put the variable we can use in the **XML (**our ViewModel in this case). We set the name and then the type, which is the reference to the class we’ll use.
Finally, we can use viewmodel.onShowAndroidJobsRequire and viewmodel.onOutAppLiveData in the onClick handlers for the Button and TextView.
Every time we click these views, the method bound to onClick will be called on the ViewModel.
MainActivity: here’s our view, which uses the MainViewModel and the layout above:
class MainActivity : AppCompatActivity() {
private val viewModel: MainViewModel by viewModel()
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.viewModel = viewModel
binding.lifecycleOwner = this
setupViewModel()
}
private fun setupViewModel() {
viewModel.showAndroidJobsLiveData.observe(this, Observer { isShow ->
when(isShow) {
true -> { startActivity(AndroidJobsListActivity.launchIntent(this)) }
}
})
First, we inject the ViewModel into the view using Koin. A simple by viewModel() gives us a reference to the ViewModel.
Since we’re using Data Binding, we need to bind it to our View. To do this, we declare lateinit var databinding because we know it will always be initialized.
In onCreate, we first set the layout of the activity on Data Binding to bind the references in the layout. Next, we set the ViewModel on Data Binding. Finally, we set the lifecycle owner on databinding so we can listen for changes in the LiveData objects in the ViewModel.
Now we set up the observers for the LiveData objects in our ViewModel. Here’s something interesting that Koin does for us. Normally, we’d have to do the following to initialize the ViewModel:
ViewModelProviders.of(this).get(MyViewModel::class.java)
But we use Koin, which does that for us, so we don’t have to repeat those steps in every new View we create to initialize our ViewModels.
Last but not least, we’ll observe the events from our LiveData objects, which are triggered by clicks on each button in the view. Both wait for true before doing anything. showAndroidJobsLiveData navigates to AndroidJobListActivity, and outLiveData simply closes the app. Here’s the flow for these actions:
button Click — > onShowAndroidJobsRequire() — > showAndroidJobsLiveData.postValue(true) — > startActivity
- List: everything we’ve done so far in the previous articles and above is so we can finally show our list of Android jobs. We’ve covered a lot, so now let’s see how it all fits together.
AndroidJobListViewModel: Remember the useCase we created back in the first article? Well, here it is in the ViewModel constructor, along with uiScheduler, which we’ll use to observe the result of our useCase.
class AndroidJobListViewModel(
val useCase: GetJobsUseCases,
val uiScheduler: Scheduler
): BaseViewModel() {
val state = MutableLiveData<ViewState<List<AndroidJob>>>().apply {
value = ViewState.Loading
}
fun getJobs(forceUpdate: Boolean = false) {
disposables += useCase.execute(forceUpdate = forceUpdate)
.compose(StateMachineSingle())
.observeOn(uiScheduler)
.subscribe(
{
//onSuccess
state.postValue(it)
},
{
//onError
}
)
}
First we have the LiveData for our StateMachine, and our initial state is Loading.
The first method, getJobs, is where we call the useCase to give us the list of jobs we’re looking for. A simple call to useCase.execute runs everything we built in the previous two articles.
As you can see, we added compose with StateMachineSingle(), which applies a transformation. In our case, it will emit the StateMachines in our call to the useCase (cmd + f ViewState if you need a refresher).
Next, we add our uiScheduler in observerOn, so we’ll observe on the UI thread. Finally, we wait for the result in subscribe and, as soon as it arrives, set its value on our LiveData. The second block is empty because we already return the error state in StateMachineSingle.
And if you’re wondering what the two callbacks in subscribe are, the first is onSuccess, and the second is onError.
Before we get to the view we’re calling the “final” one, let’s take a quick look at our adapter.
AndroidJobsAdapter: this is simply our adapter, where we bind each job in the list to the view.
class AndroidJobsAdapter: RecyclerView.Adapter<AndroidJobsAdapter.ViewHolder>() {
var jobs: List<AndroidJob> = listOf()
inner class ViewHolder(parent: ViewGroup): RecyclerView.ViewHolder(parent.inflate(R.layout.item_android_job)) {
fun bind(androidJob: AndroidJob) = with(itemView) {
txtTitle.text = androidJob.title
txtCountry.text = androidJob.country
txtYears.text = androidJob.experienceTimeRequired
chkNative.isChecked = androidJob.native
}
}
We won’t go into how an adapter works, since you’ve probably built a list at some point in your life (if you haven’t, check out the documentation).
One thing worth pointing out here is that we use the extension inflate to inflate the layout. Finally, we populate each item in the layout with data from the corresponding androidJob entity in the list.
AndroidJobsListActivity: we finally have the screen that will show our list of jobs.
class AndroidJobsListActivity: AppCompatActivity() {
private val viewModel: AndroidJobListViewModel by viewModel()
private val androidJobAdapter: AndroidJobsAdapter by inject()
private lateinit var binding: ActivityAndroidJobsListBinding
companion object {
fun launchIntent(context: Context): Intent {
return Intent(context, AndroidJobsListActivity::class.java)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_android_jobs_list)
binding.viewModel = viewModel
binding.lifecycleOwner = this
setupView()
setupRecyclerView()
setupViewModel()
}
private fun setupView() {
setSupportActionBar(binding.toolbar);
binding.toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_material)
binding.toolbar.setNavigationOnClickListener{
finish()
}
}
private fun setupViewModel() {
viewModel.getJobs()
viewModel.state.observe(this, Observer { state ->
when(state) {
is ViewState.Success -> {
androidJobAdapter.jobs = state.data
setVisibilities(showList = true)
}
is ViewState.Loading -> {
setVisibilities(showProgressBar = true)
}
is ViewState.Failed -> {
setVisibilities(showError = true)
}
}
})
}
private fun setupRecyclerView() = with(binding.recyclerView) {
layoutManager = LinearLayoutManager(context)
adapter = androidJobAdapter
}
First, we inject the ViewModel and our adapter (in the next section, I’ll show where these dependencies are provided).
We have a lauchIntent method so other views can launch this one, as we did in the previous view.
We set up Data Binding just as we did on the previous screen.
We have an action bar that we set up in setupView, including the action for going back in setNavigationOnClickListener, which closes the activity.
We use binding.toolbar because binding gives us access to the views in our layout.
In setupViewModel, we call our ViewModel to get our data, and then we have our liveDataObserver for each state.
- Success: we set the list on the adapter, make the recyclerView visible, and hide everything else.
- Loading: we show a progressBar and hide everything else.
- Failed: we show a try again button in case something goes wrong, and hide the other views.
We also set up the RecyclerView by setting its adapter to our injected androidJobAdapter **.**
Finally, we have a method that changes the visibility of the views in the layout using the extension visible.
DI (dependency injection)
This is where we keep our Koin modules, which manage our dependencies.
- PresentationModule: here we provide everything our view and ViewModels need to work.
val presentationModule = module {
factory { AndroidJobsAdapter() }
viewModel { MainViewModel() }
First, we provide our adapter, which we injected into AndroidJobsListActivity (factory creates a new instance every time one is requested).
private val androidJobAdapter: AndroidJobsAdapter by inject()
Next, something new in our Koin modules: the ViewModels. This is simply a DSL extension for our ViewModels, so we can inject them into our Views later, as we did earlier:
private val viewModel: AndroidJobListViewModel by viewModel()
private val viewModel: MainViewModel by viewModel()
Our mainViewModel has no other dependencies, so we simply provide it without passing anything to the constructor. For AndroidJobListViewModel, though, we need to pass the useCase (provided in DomainModule.kt) and AndroidSchedulers.mainThread (Android’s main thread).
But how are these modules going to work???
We need to call startKoin in the project’s Application class:
class MyModuleApplication: Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@MyModuleApplication)
We call startKoin, then provide the context followed by all the Koin modules we created in the project.
Note: Don’t forget to set the Application class in the manifest
<application android:name=”.MyModuleApplication”
SHOW ME:


Well, folks, we’ve reached the end of the first part of the series. I’m planning to write more articles based on this project, with tests and a few other things.
Still have questions? Leave a comment below and I’ll be happy to answer, or send me an email.


