Skip to content

Instantly share code, notes, and snippets.

@anstaendig
Created November 22, 2017 18:22
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 anstaendig/3bff49a3602ec9535303c4da5f71d2ab to your computer and use it in GitHub Desktop.
Save anstaendig/3bff49a3602ec9535303c4da5f71d2ab to your computer and use it in GitHub Desktop.
@Module
object RemoteModule {
@Provides
@JvmStatic
fun provideService(): Service = ServiceFactory.getService(BuildConfig.DEBUG)
}
object ServiceFactory {
private val baseUrl: String = "https://service.com/"
fun getService(isDebug: Boolean): Service {
return buildService(
buildOkHttpClient(
buildLoggingInterceptor(isDebug)
),
buildMoshiConverterFactory()
)
}
private fun buildService(
okHttpClient: OkHttpClient,
moshiConverterFactory: MoshiConverterFactory
): Service {
return Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(moshiConverterFactory)
.baseUrl(baseUrl)
.client(okHttpClient)
.build()
.create(Service::class.java)
}
private fun buildOkHttpClient(loggingInterceptor: HttpLoggingInterceptor): OkHttpClient =
OkHttpClient.Builder().apply {
addInterceptor(loggingInterceptor)
}.build()
private fun buildMoshiConverterFactory(): MoshiConverterFactory {
val moshi = Moshi.Builder()
.add(Date::class.java, Rfc3339DateJsonAdapter())
.add(KotlinJsonAdapterFactory())
.build()
return MoshiConverterFactory.create(moshi)
}
private fun buildLoggingInterceptor(isDebug: Boolean): HttpLoggingInterceptor =
HttpLoggingInterceptor().setLevel(
if (isDebug) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment