Skip to content

Commit

Permalink
[Kotlin] Make ApiClient in jvm-retrofit2 be able to use own OkHttpCli…
Browse files Browse the repository at this point in the history
…ent (#6999)

* added okHttpClient as parameter to the constructor, adapted createService

* updated sample
  • Loading branch information
tgerth authored Aug 8, 2020
1 parent 2a17625 commit d78e915
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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() {
Expand Down

0 comments on commit d78e915

Please sign in to comment.