📚 Android Components Architecture in a Modular Word
Tags: android, kotlin, architecture, opensource
Published: 2019-12-08 16:51:23

Over years Android architecture evolved to support production-quality apps on any scale focused on helping developers to design robust, testable, and maintainable apps. For that Google has promoted in the last years [Kotlin](https://developer.android.com/kotlin) as an official Android programming language impulse via a series of community-led events like [Kotlin/Everywhere](https://events.withgoogle.com/kotlin-everywhere/) and programmers Udacity courses [Kotlin Bootcamp](https://www.udacity.com/course/kotlin-bootcamp-for-programmers--ud9011). And it is not for less since the advantages are endless with respect to Java offering modern statically typed programming language that will boost your productivity and increase your developer happiness.

But first of all, if you want to check directly the project before continuing reading the introduction, you can do by accessing the following link:

https://github.com/VMadalin/kotlin-sample-app
![Github project badges](https://thepracticaldev.s3.amazonaws.com/i/hlo3q7u5f3re212cew18.png)

The programming paradigm in android has seen a drastic turn with the introduction of [Android Jetpack](https://developer.android.com/jetpack) a suite of libraries, tools, and guidance to help developers write high-quality apps easier. These components help you to follow best practices, free you from writing boilerplate code, and simplify complex tasks. That has ended up giving rise to what is known today as [Modern Android Development](https://android-developers.googleblog.com/2019/10/android-dev-summit-2019-keynote.html).

[Android Architecture Components](https://developer.android.com/topic/libraries/architecture) are part of Jetpack and are a collection of libraries that help you design robust, testable, and maintainable apps. Start with classes for managing your UI component lifecycle and handling data persistence. 

[Modular Android App Architecture](https://en.wikipedia.org/wiki/Modular_programming) presented from [Yigit Boyar](https://twitter.com/yigitboyar) and [Florina Muntenescu](https://twitter.com/fmuntenescu) in [Google I/O'19](https://www.youtube.com/watch?v=PZBg5DIzNww), is a software design technique to separate functionality into independent, interchangeable modules so that each contains everything necessary to execute a specific functionality.
The below diagram demonstrates how would an application that uses this software design technique, although if you want to see more, I recommend the following [link](https://medium.com/androiddevelopers/a-patchwork-plaid-monolith-to-modularized-app-60235d9f212e).

![Modularized app with multiple independent features what share or not the same libraries](https://thepracticaldev.s3.amazonaws.com/i/fvsy02pjz4jchlqz5ock.png)

---

Yet when it comes to combining all architecture puzzles together into simple client application it is difficult to find open-sourced app sample to follow. For this reason, I decided to build one based, apply and strictly complies with each of the following 5 points:

- A single-activity architecture, using the [Navigation component](https://developer.android.com/guide/navigation/navigation-getting-started) to manage fragment operations.
- [Android architecture components](https://developer.android.com/topic/libraries/architecture/), part of Android Jetpack forgive to project a robust design, testable and maintainable.
- Pattern [Model-View-ViewModel](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel) (MVVM) facilitating [separation](https://en.wikipedia.org/wiki/Separation_of_concerns) of development of the graphical user interface.
- [S.O.L.I.D](https://en.wikipedia.org/wiki/SOLID) design principles intended to make software designs more understandable, flexible and maintainable.
- [Modular app architecture](https://proandroiddev.com/build-a-modular-android-app-architecture-25342d99de82) allows being developed features in isolation, independently from other features.

<img src="https://thepracticaldev.s3.amazonaws.com/i/ku5yye8tqituel4wnork.gif" width="250" align="right" hspace="20">

The project presents a modern, 2019 approach to [Android](https://www.android.com/) application development using [Kotlin](https://kotlinlang.org/) and latest [tech-stack](https://github.com/VMadalin/kotlin-sample-app#tech-stack).
The goal of the project is to demonstrate best practices, provide a set of guidelines, modular application, scalable, maintainable and testable. This application may look simple, but it has all of these small details that will set the rock-solid foundation of the larger app suitable for bigger teams and long application lifecycle management.

## Application structure

One of the key benefits of modularization architecture is supposed to be clear navigation throughout the app and source code. Looking at the root folder of the project, the following structure becomes clear:

![Project structure on root folder](https://thepracticaldev.s3.amazonaws.com/i/ra2dfd705442apodoydh.png)

## Interaction between modules

Between the modules is established a dependency relationship that allows us to make an API request, access to DDBB or use a certain initialized library. Reusing the code in this way and avoiding duplicating. The below graph shows the app dependency between modules:

- :app depends on :core and indirectly depends on :features by [dynamic-features](https://developer.android.com/studio/projects/dynamic-delivery).
- :features modules depend on :commons, :core, :app and some specific utils:library that will use.
- :core and :commons only depends on possible utils on :libraries.
- :libraries don't have any dependency.

![Graph of dependencies between modules](https://thepracticaldev.s3.amazonaws.com/i/yp8t5vmgu0rs2r5h3lfd.png)

### App module
The :app module is a com.android.application, which is needed to create the App Bundle. It is also responsible for initiating the dependency graph, play core and other project global libraries, differentiating especially between different app environments.

### Core module
The :core module is a com.android.library for serving network requests or accessing to the DDBB. Providing the data source for the many features that require it.

### Features modules
The :features module are a com.android.dynamic-feature is essentially a gradle module which can be downloaded independently from the base application module. It can hold code and resources and include dependencies, just like any other gradle module.

### Commons modules
The :commons modules are a com.android.library only contains code and resources which are shared between feature modules. Reusing this way layouts, views, and other components in the different features modules, without the need to duplicate code.

### Libraries modules
The :libraries modules are a com.android.library, basically contains different utilities that can be used by the different modules.

## Architecture components
Ideally, ViewModels shouldn't know anything about Android. This improves testability, leak safety and modularity. ViewModels have different scopes than activities or fragments. While a ViewModel is alive and running, an activity can be in any of its lifecycle states. Activities and fragments can be destroyed and created again while the ViewModel is unaware.

Passing a reference of the View (activity or fragment) to the ViewModel is a serious risk. Let's assume the ViewModel requests data from the network and the data comes back sometime later. At that moment, the View reference might be destroyed or might be an old activity that is no longer visible, generating a memory leak and, possibly, a crash.

![Observer pattern in the presentation and data layer](https://thepracticaldev.s3.amazonaws.com/i/wueyenr8dxui3cb3z5jz.png)

The communication between the different layers follows the above diagram using the reactive paradigm, observing changes on components without the need of callbacks avoiding leaks and edge cases related to them.

## Configuration files
With App Modularization we want to gain fine-grained dependency control but we also need to make sure we don't end up maintaining multiple configuration files.

For that we have the following common configuration files:

- [commons/android-dynamic-feature.gradle.kts](https://github.com/VMadalin/kotlin-sample-app/blob/master/buildSrc/src/main/kotlin/commons/android-dynamic-feature.gradle.kts)
- [commons/android-library.gradle.kts](https://github.com/VMadalin/kotlin-sample-app/blob/master/buildSrc/src/main/kotlin/commons/android-library.gradle.kts)
- [commons/kotlin-library.gradle.kts](https://github.com/VMadalin/kotlin-sample-app/blob/master/buildSrc/src/main/kotlin/commons/kotlin-library.gradle.kts)

The following android-dynamic-feature.gradle.kts is applied to every feature module with the following line:

```
plugins {
    id("commons.android-dynamic-feature")
}
```

## Things to consider

Of course, nothing is perfect, especially if it has recently come out. Here are some issues what I found during development:

- Navigation component doesn't support multiple back-stack for the moment. Exist different [workarounds](https://github.com/android/architecture-components-samples/issues/530) but not officially solution to this. ([issue](https://issuetracker.google.com/issues/127932815))

- Robolectric isn't compatible with dynamic-features modules for the moment. Test on dynamic-feature throws the following exception. The same test but under android-library , works correctly. ([issue](https://github.com/robolectric/robolectric/issues/5383))

```
java.lang.RuntimeException:java.lang.UnsupportedOperationException: libraries not supported yet
```

- Roboelectric throw the following exception on testing apps with data-binding in module. ([issue](https://issuetracker.google.com/issues/126775542))

```
java.lang.NoClassDefFoundError:androidx/databinding/DataBinderMapperImpl
```

- [MockK](https://github.com/mockk) with LiveData dependency throws an exception when trying to obtain value. ([issue](https://github.com/mockk/mockk/issues/388)). The workaround is to use mockito for the moment. 

```
java.lang.ClassCastException:java.lang.Object cannot be cast to java.lang.String
```

## Additional Resources

### Projects

This is project is a sample, to inspire you and should handle most of the common cases, but obviously not all. If you need to take a look at additional resources to find solutions for your project, visit these interesting projects:

-   [iosched](https://github.com/google/iosched) (by [google](https://github.com/google)) - official Android application from google IO 2019.
-   [plaid](https://github.com/android/plaid) (by [android](https://github.com/android)) - app which provides design news & inspiration, being an example of implementing material design.
-   [sunflower](https://github.com/android/sunflower) (by [android](https://github.com/android)) - a gardening app illustrating Android development best practices with Android Jetpack.
-   [architecture-components-samples](https://github.com/android/architecture-components-samples) (by [android](https://github.com/android)) - collection of samples for Android Architecture Components.
-   [architecture-sample](https://github.com/android/architecture-samples) (by [android](https://github.com/android)) - collection of samples to discuss and showcase different architectural tools and patterns for Android apps.
-   [android-clean-architecture-boilerplate](https://github.com/bufferapp/android-clean-architecture-boilerplate) (by [bufferapp](https://github.com/bufferapp)) - an android boilerplate project using clean architecture
-   [android-kotlin-clean-architecture](https://github.com/sanogueralorenzo/Android-Kotlin-Clean-Architecture) (by [sanogueralorenzo](https://github.com/sanogueralorenzo)) - android sample Clean Architecture app written in Kotlin.
-   [modularization-example](https://github.com/JeroenMols/ModularizationExample) (by [JeroenMols](https://github.com/JeroenMols)) - easy to understand real-life example of a modularized Android app.
-   [lego-catalog](https://github.com/Eli-Fox/LEGO-Catalog) (by [Eli-Fox](https://github.com/Eli-Fox)) - app illustrating current Android Architecture state using Android development best practices.
-   [tivi](https://github.com/chrisbanes/tivi) (by [chrisbanes](https://github.com/chrisbanes)) - an app which attempts to use the latest cutting edge libraries and tools.
-   [android-showcase](https://github.com/igorwojda/android-showcase) (by [igorwojda](https://github.com/igorwojda)) - app following best practices: Kotlin, coroutines, Clean Architecture, feature modules, tests, MVVM, static analysis.

### Articles

A collection of very interesting articles related last android community tendencies and recommendations for start to take in consideration for your current/next project:

-   [Transform monolith to modularization application](https://medium.com/androiddevelopers/a-patchwork-plaid-monolith-to-modularized-app-60235d9f212e)
-   [Using the Navigation Component in a Modular World](https://medium.com/swlh/using-the-navigation-component-in-a-modular-world-e7578825962)
-   [Dependency injection in a multi module project](https://medium.com/androiddevelopers/dependency-injection-in-a-multi-module-project-1a09511c14b7)
-   [ViewModels and LiveData: Patterns + AntiPatterns](https://medium.com/androiddevelopers/viewmodels-and-livedata-patterns-antipatterns-21efaef74a54)
-   [Dynamic feature and regular modules using Dagger2](https://blog.q42.nl/dynamic-feature-and-regular-modules-using-dagger2-12a7edcec1ff)
-   [Android Architecture starring Kotlin Coroutines, Jetpack (MVVM, Room, Paging), Retrofit and Dagger 2](https://proandroiddev.com/android-architecture-starring-kotlin-coroutines-jetpack-mvvm-room-paging-retrofit-and-dagger-7749b2bae5f7)
-   [Official Kotlin Style Guide with Ktlint](https://proandroiddev.com/official-kotlin-style-guide-with-ktlint-4a649c172956)
-   [Gradle dependency management with Kotlin (buildSrc)](https://proandroiddev.com/gradle-dependency-management-with-kotlin-94eed4df9a28)
-   [Detecting Kotlin Code Smells with Detekt](https://proandroiddev.com/detecting-kotlin-code-smells-with-detekt-e79c52a35faf)
-   [Best coding practices, tips and more for Android](https://medium.com/mindorks/best-coding-practices-tips-and-more-for-android-4ec03c7eeb2c)

### Libraries

The open-source community create and maintains tons of awesome libraries making your job more easy, giving the opportunity to use them in your developments. Here are a very important collection of them:

-   [awesome-android-ui](https://github.com/wasabeef/awesome-android-ui) - collection list of awesome Android UI/UX libraries.
-   [awesome-android-libraries](https://github.com/KotlinBy/awesome-kotlin#android-libraries) - collection of awesome Kotlin related stuff.
-   [android-arsenal](https://android-arsenal.com/) - android developer portal with tools, libraries, and apps.

### Best practices

Avoid reinventing the wheel by following these guidelines:

-   [Google best practices](https://developer.android.com/distribute/best-practices)
-   [Android development best practices](https://github.com/futurice/android-best-practices)

### Codelabs

Google Developers Codelabs provide a guided, tutorial, hands-on coding experience. Most codelabs will step you through the process of building a small application, or adding a new feature to an existing application. They cover a wide range of android concepts to learn and practice:

-   [Android Developer Fundamentals](https://developer.android.com/courses/fundamentals-training/toc-v2)
-   [Android Developer Codelabs](https://codelabs.developers.google.com/?cat=Android)

---

## Summary

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/8cpcqtdws4w11a0okev4.png)

There are certain benefits in writing or migrating to Modular App and using Architecture Components with them. 

- Faster build times.
- Fine-grained dependency control.
- Improve reusability across other apps.
- Improves the ownership & the quality of the codebase.
- Stricter boundaries when compared to packages.
- Encourages Open Source of the newly created libraries.
- Makes Instant Apps & Dynamic Features possible (improving discoverability).

Remember, keeping modules [Clean](https://proandroiddev.com/clean-architecture-data-flow-dependency-rule-615ffdd79e29) improves testability and eases future refactoring in case it needs to be shared between multiple user-facing features.


---

The aim of this article was to provide a brief overview of how to combining all architecture puzzles together into your current/next project. 

If you have any questions, improvements, recommendations about modularization and architecture components please add your response 🙂.

The full open-source code can be found on GitHub:

https://github.com/VMadalin/kotlin-sample-app

[<img src="https://thepracticaldev.s3.amazonaws.com/i/tgbh1ya92nw5yr98zgd7.png">](https://www.buymeacoffee.com/vmadalin)


Thanks for your time and reading.
V.Madalin