Created
November 22, 2017 18:22
-
-
Save anstaendig/3bff49a3602ec9535303c4da5f71d2ab to your computer and use it in GitHub Desktop.
This file contains 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
@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