Let’s see how we declare dependencies in our gradle files, usually it will be like following piece of code.
Here we implemented some libraries with versions in the top level gradle file as shown below
In this way we can control all dependencies versions from one place.
Now, what if we have multiple modules in the project? Declaring same dependencies in every module is a solution to it?
No, defiantly not, then what is the solution?
Here we have to use single source of truth formula
we have to declare the libraries in one place and use them in required modules, to achieve this we use Kotlin DSL script files in android studio.
Create Kotlin DSL script file
Creating kotlin DSL script file is one of the easiest things in android. Have a look
Following code shows how to declare dependencies in above created Kotlin DSL script file.
What we have done is creating version variables for different dependencies and then create an array for each type of dependencies like navigation controller, log, image loading, etc.
Now how to use these libraries in module level gradle files, This includes two simple steps
- Add libraries.gradle file to module level gradle file with the following line
apply from: '../libraries.gradle'
2. Use the required library array as shown below
Following code shows how to implement timber and navigation controller libraries created in libraries.gradle file in any module.
Advanced Implementation tips
Using only specific dependencies from array
In basics section we learned how to implement all dependencies in an array from Kotlin DSL script file, but what if we want only specific library from array.
Let’s say we have an array of imageLoadingDependencies with glide and picasso like below
Now, the following code shows how to implement all libraries in imageLoadingDependencies array and only implement whatever I want
Arrays for modules
Implementing dependencies from DSL script file has solved the problem of declaring same dependencies multiple times but what if there is more that we can leverage from scripts
Let’s say I don’t want to implement all dependencies from DSL file instead I’ll create an array for all dependencies that needed in particular module and import it, well let’s see how it works
In the script file I’ve created an array appdependencies with all the dependency libraries that required in app module, now I just need to implement the following line in build.gradle of app module.
If there any suggestions or improvements feel free to comment
Thank you for reading.