[Kotlin] Make ApiClient in jvm-retrofit2 be able to use own OkHttpClient (#6999)

* added okHttpClient as parameter to the constructor, adapted createService

* updated sample
This commit is contained in:
tgerth 2020-08-08 14:59:41 +02:00 committed by GitHub
parent 2a17625e1f
commit d78e91517e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 4 deletions

View File

@ -48,7 +48,8 @@ import retrofit2.converter.moshi.MoshiConverterFactory
{{#nonPublicApi}}internal {{/nonPublicApi}}class ApiClient(
private var baseUrl: String = defaultBasePath,
private val okHttpClientBuilder: OkHttpClient.Builder? = null,
private val serializerBuilder: {{#gson}}Gson{{/gson}}{{#moshi}}Moshi.{{/moshi}}Builder = Serializer.{{#gson}}gson{{/gson}}{{#moshi}}moshi{{/moshi}}Builder
private val serializerBuilder: {{#gson}}Gson{{/gson}}{{#moshi}}Moshi.{{/moshi}}Builder = Serializer.{{#gson}}gson{{/gson}}{{#moshi}}moshi{{/moshi}}Builder,
private val okHttpClient : OkHttpClient? = null
) {
private val apiAuthorizations = mutableMapOf<String, Interceptor>()
var logger: ((String) -> Unit)? = null
@ -286,7 +287,9 @@ import retrofit2.converter.moshi.MoshiConverterFactory
}
fun <S> createService(serviceClass: Class<S>): S {
return retrofitBuilder.client(clientBuilder.build()).build().create(serviceClass)
var usedClient: OkHttpClient? = null
this.okHttpClient?.let { usedClient = it } ?: run {usedClient = clientBuilder.build()}
return retrofitBuilder.client(usedClient).build().create(serviceClass)
}
private fun normalizeBaseUrl() {

View File

@ -18,7 +18,8 @@ import retrofit2.converter.moshi.MoshiConverterFactory
class ApiClient(
private var baseUrl: String = defaultBasePath,
private val okHttpClientBuilder: OkHttpClient.Builder? = null,
private val serializerBuilder: Moshi.Builder = Serializer.moshiBuilder
private val serializerBuilder: Moshi.Builder = Serializer.moshiBuilder,
private val okHttpClient : OkHttpClient? = null
) {
private val apiAuthorizations = mutableMapOf<String, Interceptor>()
var logger: ((String) -> Unit)? = null
@ -171,7 +172,9 @@ class ApiClient(
}
fun <S> createService(serviceClass: Class<S>): S {
return retrofitBuilder.client(clientBuilder.build()).build().create(serviceClass)
var usedClient: OkHttpClient? = null
this.okHttpClient?.let { usedClient = it } ?: run {usedClient = clientBuilder.build()}
return retrofitBuilder.client(usedClient).build().create(serviceClass)
}
private fun normalizeBaseUrl() {