Clean Android Architecture: Take a layered approach to writing clean, testable, and decoupled Android applications
By Alexandru Dumbravan and Ed Price
()
About this ebook
As an application’s code base increases, it becomes harder for developers to maintain existing features and introduce new ones. In this clean architecture book, you'll learn to identify when and how this problem emerges and how to structure your code to overcome it.
The book starts by explaining clean architecture principles and Android architecture components and then explores the tools, frameworks, and libraries involved. You’ll learn how to structure your application in the data and domain layers, the technologies that go in each layer, and the role that each layer plays in keeping your application clean. You’ll understand how to arrange the code into these two layers and the components involved in assembling them. Finally, you'll cover the presentation layer and the patterns that can be applied to have a decoupled and testable code base.
By the end of this architecture book, you'll be able to build an application following clean architecture principles and have the knowledge you need to maintain and test the application easily.
Read more from Alexandru Dumbravan
How to Build Android Apps with Kotlin: A practical guide to developing, testing, and publishing your first Android apps Rating: 0 out of 5 stars0 ratingsHow to Build Android Apps with Kotlin.: A hands-on guide to developing, testing, and publishing your first apps with Android Rating: 0 out of 5 stars0 ratings
Related to Clean Android Architecture
Related ebooks
Mastering Kotlin for Android 14: Build powerful Android apps from scratch using Jetpack libraries and Jetpack Compose Rating: 0 out of 5 stars0 ratingsArchitecting ASP.NET Core Applications: An atypical design patterns guide for .NET 8, C# 12, and beyond Rating: 0 out of 5 stars0 ratingsReal-World Next.js: Build scalable, high-performance, and modern web applications using Next.js, the React framework for production Rating: 0 out of 5 stars0 ratingsApps and Services with .NET 8: Build practical projects with Blazor, .NET MAUI, gRPC, GraphQL, and other enterprise technologies Rating: 0 out of 5 stars0 ratingsBeginning Mobile Application Development in the Cloud Rating: 0 out of 5 stars0 ratingsJavaScript Design Patterns: Deliver fast and efficient production-grade JavaScript applications at scale Rating: 0 out of 5 stars0 ratingsLearn LLVM 12: A beginner's guide to learning LLVM compiler tools and core libraries with C++ Rating: 0 out of 5 stars0 ratingsMastering Android NDK Rating: 0 out of 5 stars0 ratingsSpring 2.5 Aspect Oriented Programming Rating: 0 out of 5 stars0 ratingsASP.NET 8 Best Practices: Explore techniques, patterns, and practices to develop effective large-scale .NET web apps Rating: 0 out of 5 stars0 ratingsKotlin In-depth [Vol-II]: A comprehensive guide to modern multi-paradigm language Rating: 0 out of 5 stars0 ratingsObject Oriented Programming with Angular: Build and Deploy Your Web Application Using Angular with Ease ( English Edition) Rating: 0 out of 5 stars0 ratingsAngular Essentials: The Essential Guide to Learn Angular Rating: 0 out of 5 stars0 ratingsSummary of Robert C. Martin's Clean Architecture Rating: 0 out of 5 stars0 ratingsProfessional Java EE Design Patterns Rating: 0 out of 5 stars0 ratingsC# Data Structures and Algorithms: Harness the power of C# to build a diverse range of efficient applications Rating: 0 out of 5 stars0 ratingsMastering UI/UX Design: Theoretical Foundations and Practical Applications Rating: 0 out of 5 stars0 ratingsAzure Bicep QuickStart Pro Rating: 0 out of 5 stars0 ratingsAngular for Enterprise Applications: Build scalable Angular apps using the minimalist Router-first architecture Rating: 0 out of 5 stars0 ratingsKubernetes from basic to advanced levels Rating: 0 out of 5 stars0 ratingsThe Art of Modern PHP 8: Learn how to write modern, performant, and enterprise-ready code with the latest PHP features and practices Rating: 0 out of 5 stars0 ratingsLearning .NET High-performance Programming Rating: 0 out of 5 stars0 ratingsJetpack Compose 1.6 Essentials: Developing Android Apps with Jetpack Compose 1.6, Android Studio, and Kotlin Rating: 5 out of 5 stars5/5
Programming For You
Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5C Programming For Beginners: The Simple Guide to Learning C Programming Language Fast! Rating: 5 out of 5 stars5/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsSQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Coding with JavaScript For Dummies Rating: 0 out of 5 stars0 ratingsBeginning Programming with C++ For Dummies Rating: 4 out of 5 stars4/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5C# 7.0 All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsPython Data Structures and Algorithms Rating: 5 out of 5 stars5/5C All-in-One Desk Reference For Dummies Rating: 5 out of 5 stars5/5Narrative Design for Indies: Getting Started Rating: 4 out of 5 stars4/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5
Reviews for Clean Android Architecture
0 ratings0 reviews
Book preview
Clean Android Architecture - Alexandru Dumbravan
BIRMINGHAM—MUMBAI
Clean Android Architecture
Copyright © 2022 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Group Product Manager: Rohit Rajkumar
Publishing Product Manager: Nitin Nainani
Senior Editor: Aamir Ahmed
Content Development Editor: Feza Shaikh
Technical Editor: Simran Udasi
Copy Editor: Safis Editing
Project Coordinator: Manthan Patel
Proofreader: Safis Editing
Indexer: Rekha Nair
Production Designer: Shyam Sundar Korumilli
Marketing Coordinator: Teny Thomas
First published: June 2022
Production reference: 2280922
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80323-458-8
www.packt.com
This book is dedicated to all the developers who went the extra mile to learn, practice, hack, innovate, and then pass their knowledge on to others. This propelled our development world forward and made this book a possibility. This book is also dedicated to all the people in my life who supported me through the times I was staring desperately at a computer screen filled with compile errors.
Alexandru Dumbravan
Foreword
If you think good architecture is expensive, try bad architecture.
— Brian Foote, CEO of HUMBL
We know deep down that this statement is true. Poorly architected code can cause problems in your application, but it can also make your code hard to understand, navigate, be improved upon, and difficult to use for other developers.
The glass is neither half empty nor half full. It’s simply larger than it needs to be.
— Grace Hopper
Grace Hopper was an American computer scientist and Navy officer. She knew the importance of a well-structured and clean architecture. They’re flexible, higher performing, far more scalable, easier to test, and you can maintain them a lot faster and more easily. A clean architecture is focused on getting the application layers built as efficiently as possible, without leaving behind (as Grace might say) leftover cup.
In a mobile application, clean architecture is more important than ever. You might find yourself battling against battery issues, memory consumption issues, security problems, compatibility, or environmental changes. Your mobile application needs to truly achieve portability.
In Clean Android Architecture, Alexandru Dumbravan applies his experience of developing Android applications for over 10 years. He takes you through a quick tour of the core software design principles and through the key features in the Android framework and supporting libraries.
Next, you’ll dig deep in data sources. It’s vital to understand the libraries and frameworks that are available for you to access and manage data. Then, Alexandru naturally transitions into data presentation. How do you present data to the user? You’ll break down how the user interface (UI) works and how to build your own UI solution.
Later, you’ll learn how to manage dependencies. Part of the value that Alexandru brings to the book is that he shows you how these different challenges were handled in the past, and what has changed over time. You’ll then see how to build the domain layer to sit in the center of your application and to control your app logic. Next, you’ll build the data layer to create and manage your data. The presentation layer handles the UI and the input/output. Finally, you’ll put the modules together and test your application.
By building an Android application with a clean architecture, you’ll be able to put every piece of your code to work, and you’ll end up with a far more scalable, performant, and maintainable application. This is a book that you’ll want to come back to, to make sure you’ve got each step of this process down. And once you do, well, we all know that the present and future is in mobile applications. So, the question is, where are you taking us?
Ed Price Senior Program Manager of Architectural Publishing Microsoft, Azure Architecture Center (http://aka.ms/Architecture)Co-Author of 7 Books, including Meg the Mechanical Engineer, The Azure Cloud Native Architecture Mapbook (Packt), and ASP.NET Core 5 for Beginners (Packt)
Contributors
About the author
Alexandru Dumbravan has been an Android developer since 2011 and has worked across a variety of Android applications that have contained features such as messaging, voice calls, file management, and file management. He continues to broaden his development skills while working in London for a popular fintech company.
About the reviewers
Revathi Gopalakrishnan is a software professional with 20 years of experience in the IT industry. She has worked extensively in mobile application development and has led various enterprise mobile enablement initiatives for large organizations and consumer applications for customers around the globe. She is also interested in emerging areas, such as machine learning, IoT, and robotic process automation. She has authored a book with Packt titled Mobile Machine Learning. Revathi resides in Chennai and enjoys spending her weekends with her husband and her two lovely daughters.
Jose Miguel is a software engineer who specializes in mobile development, with 5 years of experience. He has an Android associate developer certification from Google. He is also involved in the start-up tech community as a mentor in the OpenLab Peru community, bringing guidance to new Android developers and entrepreneurs who want to gain certain expertise in the mobile world. He resides in Lima, Peru, and enjoys watching movies, reading comics, boxing, traveling, and learning about new cultures and people around the world.
Table of Contents
Preface
Part 1 – Introduction
Chapter 1: Getting Started with Clean Architecture
Technical requirements
The architecture of a legacy app
Legacy analysis
Software design principles
SOLID principles
Component cohesion principles
Component coupling principles
Exploring the evolution of Android
Fragments
The Gradle build system
Networking
Humble objects
Functional paradigms
Kotlin adoption
Dependency injection
Android architecture components
Coroutines and flows
Jetpack Compose
Enter clean architecture
Summary
Chapter 2: Deep Diving into Data Sources
Technical requirements
Understanding Kotlin coroutines and Flows
Kotlin coroutines
Exercise 02.01 – Using Kotlin coroutines
Kotlin Flows
Exercise 02.02 – Using Kotlin Flows
Using OkHttp and Retrofit for networking
Exercise 02.03 – Using OkHttp and Retrofit
Using the Room library for data persistence
Exercise 02.04 – Using Room to persist data
Understanding and using the DataStore library
Exercise 02.05 – Using DataStore to persist data
Summary
Chapter 3: Understanding Data Presentation on Android
Technical requirements
Analyzing lifecycle-aware components
Exercise 3.1 – Using ViewModel and LiveData
Using Jetpack Compose to build UIs
Exercise 3.2 – Navigating using Jetpack Compose
Summary
Chapter 4: Managing Dependencies in Android Applications
Technical requirements
Introduction to DI
Using Dagger 2 to manage dependencies
Using Hilt to manage dependencies
Exercise 04.01 – Using Hilt to manage dependencies
Summary
Part 2 – Domain and Data Layers
Chapter 5: Building the Domain of an Android Application
Technical requirements
Introducing the app's architecture
Creating the domain layer
Exercise 05.01 – Building a domain layer
Summary
Chapter 6: Assembling a Repository
Technical requirements
Creating the data layer
Creating repositories
Exercise 06.01 – Creating repositories
Summary
Chapter 7: Building Data Sources
Technical requirements
Building and using remote data sources
Exercise 07.01 – Building a remote data source
Building and integrating local data sources
Exercise 07.02 – Building a local data source
Summary
Part 3 – Presentation Layer
Chapter 8: Implementing an MVVM Architecture
Technical requirements
Presenting data in Android applications
Presenting data with MVVM
Exercise 08.01 – Implementing MVVM
Presenting data in multiple modules
Exercise 08.02 – Multi-module data presentation
Summary
Chapter 9: Implementing an MVI Architecture
Technical requirements
Introducing MVI
Implementing MVI with Kotlin flows
Exercise 09.01 – Transitioning to MVI
Summary
Chapter 10: Putting It All Together
Technical requirements
Inspecting module dependencies
Exercise 10.01 – Reduce dependencies
Instrumentation testing
Exercise 10.02 – Instrumented testing
Summary
Other Books You May Enjoy
Preface
As an application's code base increases, it becomes harder for developers to maintain existing features and introduce new ones. In this clean architecture book, you'll learn how to identify when and how this problem emerges and how to structure your code to overcome it.
The book starts by explaining clean architecture principles and Android architecture components and then explores the tools, frameworks, and libraries involved. You'll learn how to structure your application in the Data and Domain layers, the technologies that go in each layer, and the role that each layer plays in keeping your application clean. You'll understand how to arrange the code into these two layers and the components involved in assembling them. Finally, we'll cover the Presentation layer and the patterns that can be applied to have a decoupled and testable code base.
By the end of this book, you'll be able to build an application following clean architecture principles and have the knowledge you need to maintain and test the application easily.
Who this book is for
This book is for Android developers who want to learn about managing the complexity of their applications and is also highly recommended for intermediate or advanced Android developers looking for a go-to guide for clean architecture and the integration of various Android technologies. New developers familiar with the fundamentals of Android app development will find this book useful, too.
What this book covers
Chapter 1, Getting Started with Clean Architecture, starts by presenting the evolution of Android apps with regards to how business logic was structured, and the problems caused by these approaches. It will then transition to how certain patterns were applied to tackle these issues, revealing other sets of issues. Finally, the concept of clean architecture will be introduce, as well as how its principles can be used to solve some of the problems presented previously.
Chapter 2, Deep Diving into Data Sources, covers what Android tools and frameworks are available to use with regard to the implementation of the data layer and details and expands on the ones that will be used later in the book, such as Kotlin flows and coroutines, Retrofit, Room, and DataStore.
Chapter 3, Understanding Data Presentation on Android, covers what Android tools and frameworks are available to use with regard to the implementation of the presentation layer and will detail and expand on the ones that will be used later in the book, such as Android ViewModel and Jetpack Compose.
Chapter 4, Managing Dependencies in Android Applications, provides a quick overview of dependency injection and how it works. It briefly explores some of the dependency injection tools available for Android development, ending with the Hilt dependency injection framework, about which it goes into a more detailed explanation because it will be used in many of the exercises in the book.
Chapter 5, Building the Domain of an Android Application, describes how to build a domain layer and what components are part of this layer. You will learn about entities and use cases or interactors and what roles they play when it comes to designing the architecture of your application.
Chapter 6, Assembling a Repository, covers the Data layer and the responsibilities this layer has when it comes to managing an application's data, and how it can use the Repository pattern to achieve this.
Chapter 7, Building Data Sources, continues the exploration into the Data layer and some examples of data sources that can be defined in Android. You will learn about using remote data sources to load data from various servers as well as local data sources such as Room and DataStore.
Chapter 8, Implementing an MVVM Architecture, presents the MVVM architecture pattern and how it can be used in an application's presentation layer. You will learn how to use the Android ViewModel and LiveData to build an app with MVVM and integrate use cases into the ViewModel.
Chapter 9, Implementing an MVI Architecture, presents the MVI architecture pattern and how it can be used in an application's presentation layer. You will learn how to use Kotlin flows and Android ViewModel to implement the MVI pattern.
Chapter 10, Putting It All Together, covers the benefits of clean architecture by analyzing an example of an application that implements the concepts and then adding instrumentation tests with Espresso and Jetpack Compose. The introduction of UI tests serves as a good example of how we can inject and change certain behaviors in the application for testing purposes without needing to modify the application's code.
To get the most out of this book
You'll need the Android Studio IDE installed on your computer (version Arctic Fox 2020.3.1 Patch 3 or above) and Java 8 to be installed. Using later versions of Java such as Java 11 might cause errors when building some of the exercises. Knowing how to trigger builds on an emulator or device and Gradle Synchronizations from Android Studio is recommended before attempting the exercises presented in the book.
You can expand on the final exercise of the book by optimizing the way the data is loaded, introducing in-memory caches, or integrating new network calls to fetch additional data for the users. You can also improve the instrumentation testing by adding interaction with the list of data and opening new screens and asserting that the correct data is displayed.
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book's GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
Download the example code files
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Clean-Android-Architecture. If there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Code in Action
The Code in Action videos for this book can be viewed at https://bit.ly/3LqAa30
Download the color images
We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781803234588_ColorImages.pdf
Conventions used
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: Inside the resources folder, create a subfolder called mockito-extensions. Inside this folder, create a file named org.mockito.plugins.MockMaker, and inside this file, add the text mock-maker-inline.
A block of code is set as follows:
data class User(
val id: String,
val firstName: String,
val lastName: String,
val email: String
) {
fun getFullName() = $firstName $lastName
}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
…
@Composable
fun Screen(viewModel: MainViewModel = viewModel(factory = MainViewModelFactory())) {
viewModel.uiStateLiveData.observeAsState().value?.let {
UserList(uiState = it)
}
}
…
Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: Create a new project in Android Studio using an Empty Compose Activity.
Tips or Important Notes
Appear like this.
Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Share Your Thoughts
Once you've read Clean Android Architecture, we'd love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we're delivering excellent quality content.
Part 1 – Introduction
In this part, you will become familiar with the notion of clean architecture and the principles it provides. This part also explores the tools, frameworks, and libraries used later in the book.
This part includes the following chapters:
Chapter 1, Getting Started with Clean Architecture
Chapter 2, Deep Diving into Data Sources
Chapter 3, Understanding Data Presentation on Android
Chapter 4, Managing Dependencies in Android Applications
Chapter 1: Getting Started with Clean Architecture
In this chapter, we'll take you back and show you how a feature would have been implemented in the past while analyzing the potential issues and problems with that approach. Then, we'll look at some key design principles for software development and apply those principles to our legacy examples. After that, we'll cover the evolution of the Android platform and the various libraries and frameworks that have emerged. We'll also see how they can be integrated while adhering to various software design principles.
After that, we'll introduce clean architecture so that we know what our system needs to be improved and what questions we must ask, as developers, so that we can create a robust, scalable, maintainable, and testable application.
In this chapter, we're going to cover the following main topics:
The architecture of a legacy app
Software design principles
Exploring the evolution of Android
Enter clean architecture
By the end of this chapter, you will know about the evolution of Android development, its architecture, and its design concepts, as well as the concept of clean architecture and how it can be used to build flexible, maintainable,