Gradle dependency based on both build type and flavor

Solution 1:

Android Plugin for Gradle 3.x.x

Build plugin 3.x.x uses variant-aware dependency resolution so devDebug variant of an app module will automatically use devDebug variant of its library module dependency. To answer the question, this would be enough:

implementation project(':common')

Read more here: https://developer.android.com/studio/build/dependencies.html#variant_aware

Original answer

I was able to find a solution here: https://github.com/JakeWharton/u2020/blob/master/build.gradle

More on why my original code does not suffice is available here: https://code.google.com/p/android/issues/detail?id=162285

Working solution:

configurations {
  pubDebugCompile
  devDebugCompile
  pubReleaseCompile
  devReleaseCompile
}

dependencies {
  pubReleaseCompile project(path: ':common', configuration: "pubRelease")
  devReleaseCompile project(path: ':common', configuration: "devRelease")
  pubDebugCompile project(path: ':common', configuration: "pubDebug")
  devDebugCompile project(path: ':common', configuration: "devDebug")
}

Solution 2:

First define the various build types:

buildTypes {
    pubRelease {
        //config
    }
    devRelease {
        //config
    }
}

Create a task that will be executed only for a specific buildType and flavor:

task pubReleaseTask << {
    //code
}

task devReleaseTask << {
    //code
}

You can add the dependency dynamically:

tasks.whenTaskAdded { task ->
    if (task.name == 'pubRelease') {
        task.dependsOn pubReleaseTask
    }
    if (task.name == 'devRelease') {
        task.dependsOn devReleaseTask 
    }
}

Solution 3:

Take a look at Multi-flavor variants You shouldn't use buildTypes for this. But you can define multi-flavors:

flavorDimensions "first", "second"

productFlavors {
    pub {
        flavorDimension "first"
    }
    dev {
        flavorDimension "first"
    }
    deb {
        flavorDimension "second"
    }
    rel {
        flavorDimension "second"
    }
}

And then you can add dependencies to your libs like this

pubRelCompile project(path: ':common', configuration: "pubRel")
devRelCompile project(path: ':common', configuration: "devRel")
pubDebCompile project(path: ':common', configuration: "pubDeb")
devDebCompile project(path: ':common', configuration: "devDeb")