3

My app has 3 flavors (free, paid, special) and there's a dependency LIB_1 need only for free flavor and other dependency LIB_2 needed for both paid and special flavors.

So, my question is how to define these dependencies in build.gradle file?

Currently, i define them like this:

dependencies {
    freeImplementation 'LIB_1'
    paidImplementation 'LIB_2'
    specialImplementation 'LIB_2'
}

Is there a better way to define them instead of duplicating the same dependency for different flavors?

y.allam
  • 1,446
  • 13
  • 24

2 Answers2

0

Yes, according to the documentation of android gradle dependency management, this is the only way of declaring flavor-specific dependencies.

If you are in a multi-modular project (and you don't want to repeat those lines in each submodule), you can also define these dependencies using the subproject block in the build.gradle of the root project:

subprojects {
    //all subprojects` config
}
//or
configure(subprojects.findAll {it.name != 'sample'}) {
    // subprojects that their name is not "sample"
}
Adib Faramarzi
  • 3,798
  • 3
  • 29
  • 44
0

Yes, it's possible to avoid duplicating the dependency across flavors, as I describe in my answer here: https://stackoverflow.com/a/75083956/6007104

Utility

Simply add these functions before your dependencies block:

/** Adds [dependency] as a dependency for the flavor [flavor] */
dependencies.ext.flavorImplementation = { flavor, dependency ->
    def cmd = "${flavor}Implementation"
    dependencies.add(cmd, dependency)
}

/** Adds [dependency] as a dependency for every flavor in [flavors] */
dependencies.ext.flavorsImplementation = { flavors, dependency ->
    flavors.each { dependencies.flavorImplementation(it, dependency) }
}

Usage

You use the utility like this:

dependencies {
    ...
    def myFlavors = ["flavor1", "flavor2", "flavor3"]
    flavorsImplementation(myFlavors, "com.example.test:test:1.0.0")
    flavorsImplementation(myFlavors, project(':local'))
    ...
}

How it works

The key to this utility is gradle's dependencies.add API, which takes 2 parameters:

  1. The type of dependency, for example implementation, api, flavor1Implementation. This can be a string, which allows us to use string manipulation to dynamically create this value.
  2. The dependency itself, for example "com.example.test:test:1.0.0", project(':local').

Using this API, you can add dependencies dynamically, with quite a lot of flexibility!

Luke Needham
  • 3,373
  • 1
  • 24
  • 41