Gradle dependency based on both build type and flavor

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")
}

Follow up @dooplaye's example, assume you only want to compile leanback in one flavor, you could refer to below snippet:

applicationVariants.all { variant ->
    def flavorString = ""
    def flavors = variant.productFlavors
    for (int i = 0; i < flavors.size(); i++) {
        flavorString += flavors[i].name;
    }

    if (flavorString.equalsIgnoreCase("pubdeb")) {
        dependencies {
            compile('com.android.support:leanback-v17:22.2.1')
        }
    }
}

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 
    }
}

Tags:

Android

Gradle