Unify all dependencies into one Gradle file in a multi-module Android project

Sergio Moral
3 min readJul 25, 2021

--

Photo by NASA on Unsplash

If you are here, you are asking yourself the same question I did it to myself days ago.

How the f*$% can I just add dependencies in a multimodule project without repeating them over and over? 🤷

Okay, the solution is so simple! ✌️

/ Chapter I: The problem

Days ago I started with a new project, trying to create a base application that would be a skeleton to follow in every project I will implement in the future.

Nice!

For that, I created a new Android project, added two Fragments, and added a button to navigate between them.

That was so straightforward, so I started to add more logic, like API calls, separate the project into different layers (data, domain, presentation), extensions, base classes….

I had no problem at this point, but, when I was implementing all the “base” logic I thought it will be great to separate this logic and move to another module, called core.

/ Chapter II: Modules

Hands-on! 🙌

I created a new Android library that I called core and here is where I am going to place all of this “base” code that will be used all over the application.

Once I have created my core module created I moved all the code that was placed in my app module.

The dependency tree should be something like this:

Here it was when the problem appears….

There were some functions from a third-party library that I want to use both in the app module and the core module. For that, I need to include the library in both build.gradle files.

/ Chapter III: The solution

I think this is the cleanest and easiest way to solve this.

  1. Move all the common dependencies to the core’s build.gradle file.

2. Modify the app’s build.gradle file.

And that’s all!

Just ensure that your core’s build.gradle file has this

apply plugin: 'com.android.library'

instead of

apply plugin: 'com.android.application'

at the top of the file and everything should work fine with that.

/ Chapter IV: Api instead of implementation

When we move all the common dependencies into another module, it is very common that in the app module, we need to access any functionality of one of these libraries. For that, we will add the dependencies as api, to be able to access these libraries:

There is a very good story explaining that.

api -> Can access directly

implementation -> Also add the library but not able to access directly

Hope this helps you!

Please if you have any recommendations, doubts, or whatever, please add some comments and it will be a pleasure to read you. 🤗

I have written a new story to improve the management of the gradle dependencies.

Happy coding!đź’»

--

--