Skip to content

Instantly share code, notes, and snippets.

@jimlyas
Last active January 15, 2022 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimlyas/dffb75086a5a64e12ac24f265024b34b to your computer and use it in GitHub Desktop.
Save jimlyas/dffb75086a5a64e12ac24f265024b34b to your computer and use it in GitHub Desktop.
Gist for Medium
const val DEVELOPMENT = 1
const val STAGING = 2
const val PRODUCTION = 3
@IntDef(DEVELOPMENT, STAGING, PRODUCTION)
@Retention(AnnotationRetention.SOURCE)
annotation class Environment
class EnvironmentInterceptor : Interceptor {
private val devUrl = "dev.api.com"
private val stagingUrl = "staging.api.com"
private val productionUrl = "production.api.com"
@Environment
private var env = DEBUG
override fun intercept(chain: Interceptor.Chain): Response {
val currentRequest = chain.request()
val host = when (env) {
DEVELOPMENT -> devUrl
STAGING -> stagingUrl
else -> productionUrl
}
return chain.proceed(
currentRequest.newBuilder().url(currentRequest.url.newBuilder().host(host).build())
.build()
)
}
fun setEnvironment(ctx: Context, action: () -> Unit) {
AlertDialog.Builder(ctx).apply {
setTitle("choose your environment")
setItems(arrayOf("Development", "Staging", "Production")) { dialog, which ->
env = when(which) {
0 -> DEVELOPMENT
1 -> STAGING
else -> PRODUCTION
}
action.invoke()
dialog.dismiss()
}
}.create().show()
}
}
val yourModule = module {
single(named("environment")) { EnvironmentInterceptor() }
single {
OkHttpClient.Builder().apply {
readTimeout(120, TimeUnit.SECONDS)
connectTimeout(120, TimeUnit.SECONDS)
followRedirects(false)
followSslRedirects(false)
retryOnConnectionFailure(true)
addInterceptor(get<Interceptor>(named("environment")))
}.build()
}
}
class SplashScreenActivity : AppCompatActivity {
private val envInterceptor by inject<EnvironmentInterceptor>(named("environment"))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash_screen)
envInterceptor.setEnvironment(this) {
// Call your first API here
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment