This website uses cookies to better the user experience of its visitors. Where applicable, this website uses a cookie control system, allowing users to allow or disallow the use of cookies on their computer/device on their first visit to the website. This complies with recent legislative requirements for websites to obtain explicit consent from users before leaving behind or reading files such as cookies on a user’s computer/device. To learn more click Cookie Policy.

Privacy preference center

Cookies are small files saved to a user’s computer/device hard drive that track, save, and store information about the user’s interactions and website use. They allow a website, through its server, to provide users with a tailored experience within the site. Users are advised to take necessary steps within their web browser security settings to block all cookies from this website and its external serving vendors if they wish to deny the use and saving of cookies from this website to their computer’s/device’s hard drive. To learn more click Cookie Policy.

Manage consent preferences

These cookies are necessary for the website to function and cannot be switched off in our systems. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms. You can set your browser to block or alert you about these cookies, but some parts of the site will not then work. These cookies do not store any personally identifiable information.
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us to know which pages are the most and least popular and see how visitors move around the site. If you do not allow these cookies we will not know when you have visited our site, and will not be able to monitor its performance.
Cookies list
Name _rg_session
Provider rubygarage.org
Retention period 2 days
Type First party
Category Necessary
Description The website session cookie is set by the server to maintain the user's session state across different pages of the website. This cookie is essential for functionalities such as login persistence, ensuring a seamless and consistent user experience. The session cookie does not store personal data and is typically deleted when the browser is closed, enhancing privacy and security.
Name m
Provider m.stripe.com
Retention period 1 year 1 month
Type Third party
Category Necessary
Description The m cookie is set by Stripe and is used to help assess the risk associated with attempted transactions on the website. This cookie plays a critical role in fraud detection by identifying and analyzing patterns of behavior to distinguish between legitimate users and potentially fraudulent activity. It enhances the security of online transactions, ensuring that only authorized payments are processed while minimizing the risk of fraud.
Name __cf_bm
Provider .pipedrive.com
Retention period 1 hour
Type Third party
Category Necessary
Description The __cf_bm cookie is set by Cloudflare to support Cloudflare Bot Management. This cookie helps to identify and filter requests from bots, enhancing the security and performance of the website. By distinguishing between legitimate users and automated traffic, it ensures that the site remains protected from malicious bots and potential attacks. This functionality is crucial for maintaining the integrity and reliability of the site's operations.
Name _GRECAPTCHA
Provider .recaptcha.net
Retention period 6 months
Type Third party
Category Necessary
Description The _GRECAPTCHA cookie is set by Google reCAPTCHA to ensure that interactions with the website are from legitimate human users and not automated bots. This cookie helps protect forms, login pages, and other interactive elements from spam and abuse by analyzing user behavior. It is essential for the proper functioning of reCAPTCHA, providing a critical layer of security to maintain the integrity and reliability of the site's interactive features.
Name __cf_bm
Provider .calendly.com
Retention period 30 minutes
Type Third party
Category Necessary
Description The __cf_bm cookie is set by Cloudflare to distinguish between humans and bots. This cookie is beneficial for the website as it helps in making valid reports on the use of the website. By identifying and managing automated traffic, it ensures that analytics and performance metrics accurately reflect human user interactions, thereby enhancing site security and performance.
Name __cfruid
Provider .calendly.com
Retention period During session
Type Third party
Category Necessary
Description The __cfruid cookie is associated with websites using Cloudflare services. This cookie is used to identify trusted web traffic and enhance security. It helps Cloudflare manage and filter legitimate traffic from potentially harmful requests, thereby protecting the website from malicious activities such as DDoS attacks and ensuring reliable performance for genuine users.
Name OptanonConsent
Provider .calendly.com
Retention period 1 year
Type Third party
Category Necessary
Description The OptanonConsent cookie determines whether the visitor has accepted the cookie consent box, ensuring that the consent box will not be presented again upon re-entry to the site. This cookie helps maintain the user's consent preferences and compliance with privacy regulations by storing information about the categories of cookies the user has consented to and preventing unnecessary repetition of consent requests.
Name OptanonAlertBoxClosed
Provider .calendly.com
Retention period 1 year
Type Third party
Category Necessary
Description The OptanonAlertBoxClosed cookie is set after visitors have seen a cookie information notice and, in some cases, only when they actively close the notice. It ensures that the cookie consent message is not shown again to the user, enhancing the user experience by preventing repetitive notifications. This cookie helps manage user preferences and ensures compliance with privacy regulations by recording when the notice has been acknowledged.
Name referrer_user_id
Provider .calendly.com
Retention period 14 days
Type Third party
Category Necessary
Description The referrer_user_id cookie is set by Calendly to support the booking functionality on the website. This cookie helps track the source of referrals to the booking page, enabling Calendly to attribute bookings accurately and enhance the user experience by streamlining the scheduling process. It assists in managing user sessions and preferences during the booking workflow, ensuring efficient and reliable operation.
Name _calendly_session
Provider .calendly.com
Retention period 21 days
Type Third party
Category Necessary
Description The _calendly_session cookie is set by Calendly, a meeting scheduling tool, to enable the meeting scheduler to function within the website. This cookie facilitates the scheduling process by maintaining session information, allowing visitors to book meetings and add events to their calendars seamlessly. It ensures that the scheduling workflow operates smoothly, providing a consistent and reliable user experience.
Name _gat_UA-*
Provider rubygarage.org
Retention period 1 minute
Type First party
Category Analytics
Description The _gat_UA-* cookie is a pattern type cookie set by Google Analytics, where the pattern element in the name contains the unique identity number of the Google Analytics account or website it relates to. This cookie is a variation of the _gat cookie and is used to throttle the request rate, limiting the amount of data collected by Google Analytics on high traffic websites. It helps manage the volume of data recorded, ensuring efficient performance and accurate analytics reporting.
Name _ga
Provider rubygarage.org
Retention period 1 year 1 month 4 days
Type First party
Category Analytics
Description The _ga cookie is set by Google Analytics to calculate visitor, session, and campaign data for the site's analytics reports. It helps track how users interact with the website, providing insights into site usage and performance.
Name _ga_*
Provider rubygarage.org
Retention period 1 year 1 month 4 days
Type First party
Category Analytics
Description The _ga_* cookie is set by Google Analytics to store and count page views on the website. This cookie helps track the number of visits and interactions with the website, providing valuable data for performance and user behavior analysis. It belongs to the analytics category and plays a crucial role in generating detailed usage reports for site optimization.
Name _gid
Provider rubygarage.org
Retention period 1 day
Type First party
Category Analytics
Description The _gid cookie is set by Google Analytics to store information about how visitors use a website and to create an analytics report on the website's performance. This cookie collects data on visitor behavior, including pages visited, duration of the visit, and interactions with the website, helping site owners understand and improve user experience. It is part of the analytics category and typically expires after 24 hours.
Name _dc_gtm_UA-*
Provider rubygarage.org
Retention period 1 minute
Type First party
Category Analytics
Description The _dc_gtm_UA-* cookie is set by Google Analytics to help load the Google Analytics script tag via Google Tag Manager. This cookie facilitates the efficient loading of analytics tools, ensuring that data on user behavior and website performance is accurately collected and reported. It is categorized under analytics and assists in the seamless integration and functioning of Google Analytics on the website.

Clean Architecture of Android Apps with Practical Examples

  • 106040 views
  • 8 min
  • Sep 27, 2018
Denys M.

Denys M.

Android Developer

Anastasia D.

Anastasia D.

Copywriter

Share

Writing quality code for medium and high-complexity applications requires considerable effort and experience. An application should not only meet the customer’s requirements but also be flexible, testable, and maintainable.

As a solution to these challenges, Robert C. Martin, also known as Uncle Bob, came up with the Clean Architecture concept in 2012.

In this article, we’ll review the concept of Clean Architecture in Android applications and show several code examples.

What is Clean Architecture?

Clean Architecture combines a group of practices that produce systems with the following characteristics:

  • Testable
  • UI-independent (the UI can easily be changed without changing the system)
  • Independent of databases, frameworks, external agencies, and libraries

The dependency rule is the overriding rule that makes Clean Architecture work. It says that nothing in an inner circle should depend on anything in an outer circle. In particular, application and business rules shouldn’t depend on the UI, database, presenters, and so on. These rules allow us to build systems that are simpler to maintain, as changes in outer circles won’t impact inner ones.

The Clean Architecture Model
Original Clean Architecture scheme suggested by Robert C. Martin

The original Clean Architecture scheme is rather confusing and often leads to misunderstanding of the main principles of the approach.

The following scheme is much easier to understand, as it’s presented from the UI to the backend or database:

Implementation of Clean Architecture in Android
Implementation of Clean Architecture in Android

Here’s a brief definition of some terms from the images above to help you get more familiar with this approach:

  • Entities are enterprise-wide business rules that encapsulate the most general business rules and also contain Data Transfer Objects (DTOs). When something external changes, these rules are the least likely to change.
  • Use cases are also called interactors and stand for application-specific business rules of the software. This layer is isolated from changes to the database, common frameworks, and the UI.
  • Interface adapters convert data from a convenient format for entities and use cases to a format applicable to databases and the web, for example. This layer includes Presenters from MVP, ViewModel from MVVM, and Gateways (also known as Repositories).
  • Frameworks and drivers are the outermost layer, which consists of the web framework, database, UI, HTTP client, and so on.

Now we can look at the pictures above with deeper understanding. In the first stage, the user opens the screen and the system requests data from the Presenter (or ViewModel). In the Presenter layer, the UseCase makes a request to the Repository whether there’s project data in the database.

If the result is positive, the Repository will create the project’s DTO and will return the data to UseCases. If there is no project data in the database, then the Repository will make a request in the net and save the data to the database. A UseCase, in turn, returns data to the Presenter, which returns this data to the UI where the information is rendered.

As you can see in the image, an Android application with Clean Architecture gathers the layers into three modules:

  • Presentation, which includes the UI, Presenter, and ViewModels
  • Domain, which includes Entities and Interactors
  • Data, which includes Databases and Rest clients

Technologies for implementing Clean Architecture in Android apps

Here’s a short list of technologies used in this example:

  • Kotlin ‒ A statically typed programming language for modern multi-platform applications; Google rates Kotlin a first-class language for writing Android apps
  • Dagger 2 ‒ A fully static, compile-time dependency injection framework for both Java and Android
  • RxJava 2 ‒ Reactive Extensions for the Java Virtual Machine (JVM) – a library for composing asynchronous and event-based programs using observable sequences for the JVM
  • Retrofit 2 ‒ A type-safe HTTP client for Android and Java

Along with the Clean Architecture approach, the following Android architecture components will also be used in the application:

  • Room ‒ Provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite
  • ViewModel ‒ Designed to store and manage UI-related data in a life cycle-conscious way
  • LiveData ‒ An observable data holder class that, unlike a regular observable, is life cycle-aware, meaning it respects the lifecycle of other app components such as activities, fragments, and services
  • Paging Library ‒ Makes it easier for you to load data gradually and gracefully within your app’s RecyclerView

Clean Android architecture approach in practice

Now let’s see how to implement Clean Architecture in Android applications.

To start, we need to create three modules: Presentation (an app in our case), Data, and Domain.

Implementation of Clean Architecture in Android

Domain

In this module we’ll place all objects that will interact with other layers.

Data Transfer Objects (DTOs) are usual Kotlin data classes:

The Repository is an interface that describes incoming parameters and the type of the object returned. Below, you can see an example of ProjectRepository:

ViewModel interacts with UseCases. It forms an object with the necessary parameters described in UseCase and makes a request which returns either an expected result or an error. UseCase acts not only as an intermediary between the ViewModel and Repository but can also request data from various Repositories and combine it or apply additional calculations. Developers can create several types of UseCases based on the base class for different purposes. For example, GetProjectListUseCase:

Data

The Data module includes RestClient, Database, adapters, and so on.

Repository implementation

Implementation of a repository provides access to data with the ability to select a data source depending on the conditions.

Adapters

The main task of adapters is to convert the entities used by the database and network clients to Domain module entities and back. This conversion has both pros and cons:

  • Any data changes in one layer don’t affect other layers
  • Third-party dependencies as well as annotations required for a library don’t fall into other layers
  • There’s a possibility of multiple duplications
  • While changing the data you have to change the mapper

A detailed RestClient and AppDatabase implementation is provided in the project repository.

Presentation

The Presentation module includes ViewModels and the UI. In addition, we connect all dependencies from our DI in this module.

In order to avoid memory leaks when using UseCases, we need to unsubscribe from all UseCases. That’s why we use ViewModel for simplified life cycle processing. For even more convenience, we’ll create an abstract BaseViewModel class. After that, we’re able to create a subclass where all UseCases will be driven to the base constructor. Finally, we’ll unsubscribe from all UseCases in ViewModel.

In order to connect the dependencies in ViewModel, the developer needs to create ViewModelFactory, which will get all required dependencies in the constructor with the help of @Inject annotation. Then this model will create the required ViewModel with these dependencies in the create function.

With the help of the ready-made ViewModelFactory pattern made in Activity with DI, we create the ViewModel. After that, we can request and observe data coming into the ViewModel.

PagingLibrary with Clean Architecture

If you want to use PagingLibrary with Clean Architecture in an Android application, you’ll face a problem because they both use their own data sources. As it’s impossible to make a request to the network or database in the Presentation layer, you’ll need to use data sources described in the Data layer through the ViewModel. In this case, you just need to delegate all requests from PagingLibrary to the ViewModel.

As in our case there’s no need for PagingLibrary to request data in another thread (UseCases control this themselves), we can create a MainThreadExecutor that will be used for the setBackgroundThreadExecutor function and the setMainThreadExecutor function.

When using the UseCases described above, take into account that the execute method can be called several times. For instance, when entering a search phrase on the screen, a request will be sent to the network after each entered character and short debounce. And as requests are made asynchronously, the result of the first request may come last. This can lead to inconsistency between the text entered and the data found. This problem might be solved by increasing the debounce time, but sometimes that can even hurt the user experience more. The best solution in this case is to make unsubscribing from the previous request compulsory when making a new request.

When we use Single Repository and RxJava patterns, a problem with error processing appears. When an error occurs in one of the requests, the data may not come in time from the database and UseCase will return an error. To solve this issue, you can use the RxJava mergeDelayError method instead of the usual merge. In this case, when we observe some changes in the database we won’t get an error at all as onComplete won’t be called.

The problem will be solved by separating one UseCase into two. The first one will command the repository to make a request and save the received data to the database; the second will call back the required data from the first request and will observe all changes in the database. This way we can always call data back from the database and process the network error.

Key takeaways

To sum up, Clean Architecture is a great solution for building medium and high-complexity applications that will receive further support. It’s compatible with MVP and MVVM and works well with Android Architecture Components. Using this architecture for building simple apps may lead to overengineering, however.

CONTENTS

Authors:

Denys M.

Denys M.

Android Developer

Anastasia D.

Anastasia D.

Copywriter

Rate this article!

Nay
So-so
Not bad
Good
Wow
27 rating, average 4.67 out of 5

Share article with

Comments (8)
Adenle Babajide Mubaraq
Adenle Babajide Mubaraq over 5 years ago
Thanks a lot for this educative article
Reply
Anastasia Z.
Anastasia Z. over 5 years ago Adenle Babajide Mubaraq
Hi there! Thanks for your kind feedback ;)
Reply
Ali Mehrpour
Ali Mehrpour about 5 years ago
Great article. thanks for sharing!
Reply
Anastasia Z.
Anastasia Z. about 5 years ago Ali Mehrpour
Hi there! Thanks for your kind feedback ;)
Reply
Doan Dinh
Doan Dinh about 5 years ago
It would be great if you guys can push completed example code. Btw, thanks for sharing!
Reply
Maryna Z.
Maryna Z. about 5 years ago Doan Dinh
Hi there! Thanks for your feedback. We'll consider your suggestion, stay tuned :)
Reply
Ahmed M Bader El Din
Ahmed M Bader El Din over 4 years ago
Great article. thanks for sharing ^_^
Reply
Amr Mustafa
Amr Mustafa over 4 years ago
Great article. Thanks for sharing!
Reply

Subscribe via email and know it all first!