From b929556f6adbb03ab270b3c7cb824808076e5ec4 Mon Sep 17 00:00:00 2001 From: ruirui1128 <654453664@qq.com> Date: Wed, 14 Sep 2022 16:35:20 +0800 Subject: [PATCH] =?UTF-8?q?okHttpClient=20=E5=8D=95=E4=BE=8B=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 在有些项目中, 网络请求可能不止一个apiService,很有可能是多个api,如UserApiService, OrderApiService,BuyCartApiService,再Api单例化的时候,okHttpClient 会创建多个对象,影响性能。因此okHttpClient 需要单例化。当然在此项目中只有一个apiService,并没有此问题。 --- .../hgj/jetpackmvvm/network/BaseNetworkApi.kt | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/JetpackMvvm/src/main/java/me/hgj/jetpackmvvm/network/BaseNetworkApi.kt b/JetpackMvvm/src/main/java/me/hgj/jetpackmvvm/network/BaseNetworkApi.kt index ce95378..5ac764a 100644 --- a/JetpackMvvm/src/main/java/me/hgj/jetpackmvvm/network/BaseNetworkApi.kt +++ b/JetpackMvvm/src/main/java/me/hgj/jetpackmvvm/network/BaseNetworkApi.kt @@ -33,12 +33,19 @@ abstract class BaseNetworkApi { /** * 配置http */ - private val okHttpClient: OkHttpClient - get() { - var builder = RetrofitUrlManager.getInstance().with(OkHttpClient.Builder()) - builder = setHttpClientBuilder(builder) - return builder.build() - } +// private val okHttpClient: OkHttpClient +// get() { +// var builder = RetrofitUrlManager.getInstance().with(OkHttpClient.Builder()) +// builder = setHttpClientBuilder(builder) +// return builder.build() +// } + + private val okHttpClient by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { + var builder = RetrofitUrlManager.getInstance().with(OkHttpClient.Builder()) + builder = setHttpClientBuilder(builder) + builder.build() + } + }