MindOrks

Our community publishes stories worth reading on Android Development

Follow publication

Clean Architecture in Android

--

In this article, we are going to implement the uncle bob’s clean architecture with the MVVM design pattern in our sample android app which fetches data from the local and remote databases.

Flow diagram:

In the above diagram, we are excluding the UI/View layer which contains our MainActivity.

In Data/Model layer:

we have the following:

local:

  • PreferenceManager.kt contains the logic for storing and fetching the data from the Shared Preference file.
  • LocalSource.kt is an interface:
  • Local.kt overrides the above interface:

This Local class contains getLocalData() function which fetches the data from the Shared Preference file and the logic of that presents in getDataFromLocal() in PreferenceManager class.

remote:

  • We are skipping the details of retrofit implementation which are included in ApiClient.kt, ApiInterface.kt and GetNetworkData.kt.
  • RemoteSource.kt is an interface:
  • Remote.kt overrides the above interface:

This Remote class contains getRemoteData() function which fetches the data from the remote database and the logic of that presents in getNetworkData() in GetNetworkData class.

Note:

We have one more class named DataRepository.kt:

As per DI rule, this class contains the dependencies of LocalSource and RemoteSource interface and the functions to fetch the data from local and remote.

In the Domain layer:

We have the following:

entities:

It contains the data/POJO classes.

usecases:

It contains the classes:

  • GetLocalData

It contains the dependency of DataRepository class using which we can access the data from the local database.

  • GetRemoteData

It contains the dependency of DataRepository class using which we can access the data from the remote database.

In ViewModel:

Now, in our ViewModel we are going to access the local and remote data by following:

In UI:

We have the MainActivity where we display the requested data.

Benefits of clean architecture:

  • It makes our code more testable. E.g. The business rules can be tested without the UI, Database, Web Server, or any other external element.
  • The UI can change easily, without changing the rest of the system.
  • Business logic/ViewModel simply doesn’t know anything at all about the outside world.

--

--

MindOrks
MindOrks

Published in MindOrks

Our community publishes stories worth reading on Android Development

Sachin Kumar
Sachin Kumar

Written by Sachin Kumar

Senior Java Backend Dev | Expertise in Java Microservices, Spring Boot Framework & Android apps development.

Responses (7)

Write a response