Android modularization, part 2
Part two explores the Android app’s data module, its local and remote data sources, and the repository implementation.

Editorial translation by Impulso.
MVVM, Koin, Rx, Room, Databinding, and a little more…
In the first article in the series, we set up the project and created our domain module.
- Domain
- Data
- Presentation
Data Module
Every Android project has data that needs to come from somewhere, and that’s exactly what the data module handles for us. This data can come from anywhere, such as an API or a database.
When the domain module requests data, it doesn’t know where the data comes from, because that’s the responsibility of the data module.
What’s in the data module:
- Api: this contains all the endpoints we’ll use to request data from the backend.
- Model: this contains the entities that come from the backend or the cache, in other words, the raw data used only in the data module.
- Mapper: this is where we map our models to the entities required by the domain module.
- RepositoryImpl: this is where we implement the interface for the repository in the domain module and decide whether to fetch the data from the cache or the backend.
- CacheDataSource: the communication interface implemented by our cache to retrieve data locally.
- CacheDataSourceImpl: this is where we save the data in the cache (in our case, a Room database) and return it after mapping it**.**
- RemoteDataSource: the communication interface implemented by the remote source to retrieve data from the backend.
- RemoteDataSourceImpl: this is where we call our server API to fetch data from the backend and map it before returning it to the caller.
Flow diagram for the data module:

The domain module requests data from its repository, which is implemented in RepositoryImpl, which then decides where to fetch the requested data.
First, we check the cache to see if there’s any data to return. If there isn’t, we call the remote source and save the data in the cache. Then we return the requested data to the domain module.

Now that we have an idea of how our data module works, let’s create it. The process is almost exactly the same as in the previous article. The only difference is that instead of selecting Java Library, we’ll select Android Library.
Let’s start building the module:
The first thing we’ll do is add the necessary dependencies to our dependencies.gradle file for the data module.
To make calls to the backend, we’ll use Retrofit, and for our cache we’ll use Room.
We won’t go into these libraries in depth, so we’ll explain them briefly as we build the module. If you have questions, check the links throughout the article for more on how to use them. If you still have questions, feel free to get in touch.
Here’s what our updated dependencies will look like:
ext {
//Android Config
minSDK = 20
targetSDK = 28
compileSDK = 28
kotlinVersion = '1.3.21'
buildTools = '3.4.0-beta04'
//Rx
rxJavaVersion = '2.2.7'
rxKotlinVersion = '2.2.0'
rxAndroidVersion = '2.1.1'
//Koin
koinVersion = '1.0.2'
//Retrofit
retrofitVersion = '2.3.0'
//Gson
gsonVersion = '2.8.5'
//Room version
roomVersion = '2.1.0-alpha02'
Note: Feel free to use different versions or other libraries. The concept is independent of the libraries you use.
Now let’s declare our libraries in the Gradle file for the data module:
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
android {
def globalConfiguration = rootProject.extensions.getByName("ext")
compileSdkVersion globalConfiguration["compileSDK"]
defaultConfig {
minSdkVersion globalConfiguration["minSDK"]
targetSdkVersion globalConfiguration["targetSDK"]
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
def dependencies = rootProject.ext.dependencies
implementation project(":domain")
implementation dependencies.kotlin
implementation dependencies.rxJava
implementation dependencies.retrofit
implementation dependencies.retrofitRxAdapter
implementation dependencies.retrofitGsonConverter
implementation dependencies.gson
implementation dependencies.room
implementation dependencies.roomRxJava
kapt dependencies.roomCompiler
You may not have noticed, but we added 3 properties to the dependencies: minSdk, targetSdk, and compileSdk, which are used in the Gradle file for the data module.
This module depends on the domain module because this is where we implement the repositories that return the data we’re fetching.
Now that the dependencies are configured, we can start building our module.
As we saw earlier, we’ll display a list of AndroidJobs at the end:
{
"jobs": [{
"title": "Android developer",
"native": true,
"required_experience_years": 3,
"country": "Brazil"
},
…
]
}
CacheData
Let’s start by implementing our cache and getting it ready to store our data:
- Model: this is where we create the entity we’ll use in our database.
@Entity(tableName = "jobs")
data class AndroidJobCache(
@PrimaryKey(autoGenerate = true)
var id: Int = 0,
var title: String = "",
var requiredExperienceYears: Int = 0,
var native: Boolean = false,
var country: String = ""
)
Here’s the entity we’ll use in our database.
- DataBase: we need to create our database and have a way to interact with it. For that, we have two classes:
JobsDao: our interface for interacting with the database, as the name “DAO” suggests (Data Access Object):
@Dao
interface JobsDao {
@Query("SELECT * FROM jobs")
fun getJobs(): Single<List<AndroidJobCache>>
@Transaction
fun updateData(users: List<AndroidJobCache>) {
deleteAll()
insertAll(users)
}
@Insert
fun insertAll(users: List<AndroidJobCache>)
We have 4 methods for interacting with the database:
- getJobs: returns a list of AndroidJobsCache from the jobs table (which we defined earlier with Entity(“tableName = jobs”)).
- inserAll: inserts a list of AndroidJobs into the jobs table.
- deleteAll: deletes all data from the jobs table.
- updateData: deletes the old data and replaces it with the new data we received.
JobsDataBase: this is simply the class that creates our database:
@Database(version = 1, entities = [AndroidJobCache::class])
abstract class JobsDataBase : RoomDatabase() {
abstract fun jobsDao(): JobsDao
Here we create our database, reference the entity we created earlier, and set up our jobsDao to access the data in the database. The createDataBase method creates our database. If you’d like to learn more about Room, I recommend the following article.
- Mapper: here we map data before saving it in the cache and map it again when reading it from the cache so it can be returned in the right format.
object AndroidJobCacheMapper {
fun map(cacheData: List<AndroidJobCache>) = cacheData.map { map(it) }
private fun map(cacheData: AndroidJobCache) = AndroidJob(
title = cacheData.title,
experienceTimeRequired = cacheData.requiredExperienceYears,
native = cacheData.native,
country = cacheData.country
)
fun mapJobsToCache(jobs: List<AndroidJob>) = jobs.map { map(it) }
The mapper is simply an object class with functions for mapping the data. You can see it in use in the following interface, JobsCacheSourceImpl, in the implementation of getJobs.

When we receive the jobs in getDao, they come in as database entities, but what we need to return is a list of AndroidJobs;
To do that, inside map we call AndroidJobCacheMapper.map(DATA), passing in the data that getDao returned (represented here by it, the list of jobs in the database**)** so it can be mapped to a List, which is what getJobs needs to return.
- Source: this consists of an interface that requests data from the cache and its implementation.
- JobsCacheDataSource: the interface the repository uses to request data from the cache.
interface JobsCacheDataSource {
fun getJobs(): Single<List<AndroidJob>>
getJobs: returns the list of AndroidJobs mapped from the database.
insertData: inserts our list of AndroidJobs into the database.
updateData: updates our database.
- JobsCacheSourceImpl: this is the implementation of the interface above.
class JobsCacheSourceImpl(private val jobsDao: JobsDao): JobsCacheDataSource {
override fun getJobs(): Single<List<AndroidJob>> {
return jobsDao.getJobs()
.map { AndroidJobCacheMapper.map(it) }
}
override fun insertData(list: List<AndroidJob>) {
jobsDao.insertAll(AndroidJobCacheMapper.mapJobsToCache(list))
}
In each implementation, jobsDao performs the requested operation. In insert and update, we map the data before saving it in our cache. In getJobs, we map the data from the cache to the required type. The jobsDao is injected through the constructor.
RemoteData
Now that we have our cache, let’s get ready to receive data from the backend.
- Model: the raw data that comes from the backend.
class JobsPayload(
@SerializedName("jobs") val jobsPayload: List<AndroidJobPayload>
)
These are the entities that represent the JSON we get from the backend, in other words, the raw data.
- Api: simply the interface that contains the endpoints we’ll call to communicate with the backend.
interface ServerApi {
We have just one call, and we specify that it should return JobsPayload.
- Mapper: here we take the raw data from the backend, our payloads, and map it to AndroidJobs, which is what the domain module requests.
object AndroidJobMapper {
fun map(payload: JobsPayload) = payload.jobsPayload.map { map(it) }
Simply an object class with functions for mapping the data.
- Source: this consists of an interface that requests data from the backend and its implementation:
- RemoteDataSource: the interface the repository uses to request data from the backend.
interface RemoteDataSource {
fun getJobs(): Single<List<AndroidJob>>
}
getJobs: returns the list of AndroidJobs, mapped from the backend.
- RemoteDataSourceImpl: the implementation of the interface above.
class RemoteDataSourceImpl(private val serverApi: ServerApi):
RemoteDataSource {
In the implementation of getJobs, we call an endpoint on the Api to request data from the backend. Once we receive it, we map the payload to the requested data. The serverApi is injected through the constructor.
RepositoryImpl
- AndroidJobsRepositoryImpl: we’ve finally reached the implementation of AndroidJobsRepository from the domain module, inside the data module.
class AndroidJobsRepositoryImpl(
private val jobsCacheDataSource: JobsCacheDataSource,
private val remoteDataSource: RemoteDataSource
): AndroidJobsRepository {
override fun getJobs(forceUpdate: Boolean): Single<List<AndroidJob>> {
return if (forceUpdate)
getJobsRemote(forceUpdate)
else
jobsCacheDataSource.getJobs()
.flatMap { listJobs ->
when{
listJobs.isEmpty() -> getJobsRemote(false)
else -> Single.just(listJobs)
}
}
}
The only method we need to implement here is getJobs, which should return a list of AndroidJobs.
First, we check whether we need to force an update. If so, we call getJobsRemote, which calls remoteDataSource to fetch data from the backend, then saves or updates it in the cache through jobsCacheDataSource.
If a forced update isn’t requested, we get the list from the cache. If it’s empty, we call getJobsRemote, save the data in the cache, and return our list.
Di (dependency injection)
This is where we keep our Koin modules, which manage our dependencies.
- DataCacheModule: manages the cache dependencies.
val cacheDataModule = module {
single { JobsDataBase.createDataBase(androidContext()) }
factory<JobsCacheDataSource> { JobsCacheSourceImpl(jobsDao = get()) }
}
First, we create an instance of our database as a single, so it’s created only once during the app’s lifecycle.
We call JobsDataBase.createDatabase to create this instance for us.
Next, we create our cache provider as a factory, so a new instance is created each time it’s requested. We register the provider under the interface and pass the required dependency to the constructor of the implementing class (in this case, the jobsDao created through JobsDataBase.createDatabase).
- DataRemoteModule: manages the backend dependencies.
val remoteDataSourceModule = module {
factory { providesOkHttpClient() }
single { createWebService<ServerApi>(
okHttpClient = get(),
url = androidContext().getString(R.string.base_url)
) }
factory<RemoteDataSource> { RemoteDataSourceImpl(serverApi = get()) }
}
fun providesOkHttpClient(): OkHttpClient {
return OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build()
}
As you can see, we create our webService and httpClient, both of which are part of the Retrofit setup. So I recommend this article if you haven’t worked with Retrofit.
In the createWebService method, we first supply our OkHttpClient when creating the webService. Then we pass the ServerApi interface as a reified type parameter, which lets us use it inside the function. We also pass in our base URL from the resources.
This method provides our webService, which can be requested by any class that has serverApi in its constructor. Then we have one last factory, registered under the RemoteDataSource interface and backed by RemoteDataSourceImpl, which takes the required dependency (in this case, serverApi) in its constructor.
Questions about Koin: https://insert-koin.io/docs/2.0/getting-started/android/ While working on this article, we switched to Koin version 2.0-rc1
- DataModule: finally, we define the repository dependency.
val repositoryModule = module {
factory<AndroidJobsRepository> {
AndroidJobsRepositoryImpl(
jobsCacheDataSource = get(),
remoteDataSource = get()
)
}
}
Now that we’ve created the dependencies our repository needs, we create a Koin module that receives them. As we explained earlier, the factory creates a new instance each time it’s requested.
Finally, we define a variable called dataModule to bring the Koin modules together in one place.
We’ve finally reached the end of another chapter in this series. I didn’t expect this part to be so long, but I think it was worth going through every step.
You can find the complete code in this GitHub repository.


