Skip to content

Instantly share code, notes, and snippets.

@0xtmphey
Last active October 9, 2019 08:06
Show Gist options
  • Save 0xtmphey/e74dd1118fd6de30751067965fc9c49f to your computer and use it in GitHub Desktop.
Save 0xtmphey/e74dd1118fd6de30751067965fc9c49f to your computer and use it in GitHub Desktop.
class EnvironmentManager(
// We use shared prefs to save currently selected env between app launches
private val store: SharedPreferences
) {
// This is a key for saving env in prefs
private val currentEnvironmentKey = "current_environment"
/*
* Here we need to describe all our strings
* for all of the supported environments.
* I use mapping `Env -> EnvVars`, but you can use anything
* (database, files, etc)
*/
private val parameters: Map<Environment, EnvironmentVariables> = mapOf(
Environment.DEVELOPMENT to EnvironmentVariables(
baseUrl = "https://api-dev.myproject.com",
algoliaSearchKey = "dev_search_key"
),
Environment.PRODUCTION to EnvironmentVariables(
baseUrl = "https://api.myproject.com",
algoliaSearchKey = "prod_search_key"
)
)
/*
* Here is an interesting part.
* We use `currentEnvironment` variable to store and retrieve current env from
* SharedPreferences and decide which variables to pull depending on Environment.
*
* We will explore `BuildConfig.DEFAULT_ENV` later on.
*/
var currentEnvironment: Environment
get() {
val default = Environment.create(BuildConfig.DEFAULT_ENV)
val current = store.getString(currentEnvironmentKey, null)?.let {
Environment.create(it)
}
return current ?: default
}
set(value) {
store.edit().putString(currentEnvironmentKey, value.id).apply()
}
// This one allows to pull desired variable just by property reference
fun get(property: KProperty1<EnvironmentVariables, String>): String {
val params = parameters[currentEnvironment] ?: throw Exception("Unsupported ENV $currentEnvironment")
return property.get(params)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment