Skip to content

Instantly share code, notes, and snippets.

@reactivedroid
Last active October 9, 2022 07:48
Show Gist options
  • Save reactivedroid/2a7ba19c6af18fbecfacfe4d38661330 to your computer and use it in GitHub Desktop.
Save reactivedroid/2a7ba19c6af18fbecfacfe4d38661330 to your computer and use it in GitHub Desktop.
Build Gradle File showing the changes to enable dynamic configuration switching feature
android {
...
defaultConfig {
// Generate all the keys on BuildConfig.java
Config.keyList.forEach { key ->
buildConfigField("String", "KEY_$key", "\"$key\"")
}
}
applicationVariants.all {
// Handling the release variant separately to create RELEASE_MAP such that our release variants
// don't have any other configurations other than their own flavor.
if (buildType.name == "release") {
buildConfigField(
"java.util.Map<String,String>", "RELEASE_MAP", variantFields(flavorName)
)
defaultFlavors.forEach { value ->
buildConfigField(
"java.util.Map<String,String>",
"${value.toUpperCase()}_MAP",
"null"
)
}
buildConfigField("java.util.ArrayList<String>", "SET_OF_FLAVORS", "null")
} else {
buildConfigField("java.util.Map<String,String>", "RELEASE_MAP", "null")
defaultFlavors.forEach { value ->
buildConfigField(
"java.util.Map<String,String>",
"${value.toUpperCase()}_MAP",
variantFields(value)
)
}
buildConfigField("java.util.ArrayList<String>", "SET_OF_FLAVORS", flavorList())
}
}
...
}
/**
* Returns the [ArrayList] of all build flavors as a `String`
*/
fun flavorList(): String {
val flavorBuilder = StringBuilder()
defaultFlavors.forEach {
flavorBuilder.append("add(\"$it\");")
}
return "new java.util.ArrayList() {{$flavorBuilder}}"
}
/**
* Returns the [HashMap] of all build configurations as a `String` for a given [flavor]
*/
fun variantFields(flavor: String): String {
val fields = variantFieldMap[flavor]
val fieldsBuilder = StringBuilder("")
fields!!.forEach { entry ->
fieldsBuilder.append("put(\"${entry.key}\",\"${entry.value}\");")
}
return "new java.util.HashMap() {{$fieldsBuilder}}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment