Created
February 17, 2019 23:22
-
-
Save CostaFot/365aa87b9922cef05a8420128f41d5a6 to your computer and use it in GitHub Desktop.
Generic repository
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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