Skip to content

Instantly share code, notes, and snippets.

@Slowhand0309
Created June 3, 2018 22:34
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 Slowhand0309/bdab4bac812ca2aeedcceda268a8f701 to your computer and use it in GitHub Desktop.
Save Slowhand0309/bdab4bac812ca2aeedcceda268a8f701 to your computer and use it in GitHub Desktop.
Retrofit+Rx+Moshi+Log sample.
object ServiceGenerator {
private lateinit var moshi: Moshi
private lateinit var retrofit: Retrofit
/**
* Initialize{@link Moshi}and{@link Retrofit}
*/
fun init(context: Context?) {
moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
val httpClientBuilder = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS) // Modify as necessary
// log
val logInterceptor = HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY)
if (!httpClientBuilder.interceptors().contains(logInterceptor)) {
httpClientBuilder.addInterceptor(logInterceptor)
}
retrofit = Retrofit.Builder()
.baseUrl(context?.getString(R.string.base_url) ?: "") // Modify as necessary
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
.client(httpClientBuilder.build())
.build()
}
fun <T> createService(serviceClass: Class<T>): T
= retrofit.create(serviceClass)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment