Created
June 3, 2018 22:34
-
-
Save Slowhand0309/bdab4bac812ca2aeedcceda268a8f701 to your computer and use it in GitHub Desktop.
Retrofit+Rx+Moshi+Log sample.
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
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