Skip to content

Instantly share code, notes, and snippets.

@CostaFot
Created February 17, 2019 23:22
Show Gist options
  • Save CostaFot/365aa87b9922cef05a8420128f41d5a6 to your computer and use it in GitHub Desktop.
Save CostaFot/365aa87b9922cef05a8420128f41d5a6 to your computer and use it in GitHub Desktop.
Generic repository
open class Repository(
baseUrl: String,
isDebugEnabled: Boolean,
apiKey: String
) {
private val apiKeyHeader: String = "x-api-key"
val retrofit: Retrofit
init {
/*adding a logging interceptor when debug is true.
you can check how your API call is going in the LogCat */
val loggingInterceptor = HttpLoggingInterceptor()
if (isDebugEnabled) {
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
} else {
loggingInterceptor.level = HttpLoggingInterceptor.Level.NONE
}
// here's how you can add your api key as a header
val client = OkHttpClient.Builder().addInterceptor { chain ->
val request = chain.request().newBuilder()
.addHeader(apiKeyHeader, apiKey)
.build()
chain.proceed(request)
}.addInterceptor(loggingInterceptor)
.build()
retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.client(client)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment