Skip to content

Instantly share code, notes, and snippets.

@marcelpinto
Last active July 21, 2018 19:01
Show Gist options
  • Save marcelpinto/5e7ef169a40c0d5711afadbc6423417b to your computer and use it in GitHub Desktop.
Save marcelpinto/5e7ef169a40c0d5711afadbc6423417b to your computer and use it in GitHub Desktop.
Testing your Network
class NetworkFactory(moshi: Moshi, authInterceptor: AuthenticationInterceptor, authenticator: Authenticator) {
private val okHttpClient: OkHttpClient
private val retrofitBuilder: Retrofit.Builder
init {
val level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
val loggingInterceptor = HttpLoggingInterceptor().setLevel(level)
okHttpClient = OkHttpClient.Builder()
.addInterceptor(authInterceptor)
.addInterceptor(loggingInterceptor)
.authenticator(authenticator)
.build()
retrofitBuilder = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
}
fun <T> createApi(apiClass: Class<T>, baseUrl: String, interceptors: List<Interceptor> = emptyList()): T {
if (interceptors.isNotEmpty()) {
val newClient = okHttpClient.newBuilder()
interceptors.forEach {
newClient.addInterceptor(it)
}
retrofitBuilder.client(newClient.build())
}
return retrofitBuilder.baseUrl(baseUrl).build().create(apiClass)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment