Skip to content

Commit 81996b2

Browse files
authored
Make sure we only have one retrofit and okhttpclient instead of 2 (#6397)
1 parent 991478d commit 81996b2

File tree

1 file changed

+22
-11
lines changed

1 file changed

+22
-11
lines changed

common/src/main/kotlin/io/homeassistant/companion/android/common/data/HomeAssistantApis.kt

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,16 @@ import okhttp3.OkHttpClient
1515
import okhttp3.logging.HttpLoggingInterceptor
1616
import retrofit2.Retrofit
1717
import retrofit2.converter.kotlinx.serialization.asConverterFactory
18+
import javax.inject.Singleton
1819

20+
/**
21+
* Provides shared HTTP infrastructure for communicating with Home Assistant servers.
22+
*
23+
* This class is a singleton to ensure a single [OkHttpClient] and [Retrofit] instance
24+
* are shared across the app. This enables proper connection pooling, reduces memory usage,
25+
* and ensures consistent configuration (timeouts, interceptors, TLS) for all API calls.
26+
*/
27+
@Singleton
1928
class HomeAssistantApis @Inject constructor(
2029
private val tlsHelper: TLSHelper,
2130
@ApplicationContext private val appContext: Context,
@@ -73,16 +82,18 @@ class HomeAssistantApis @Inject constructor(
7382
return builder
7483
}
7584

76-
val retrofit: Retrofit = Retrofit
77-
.Builder()
78-
.addConverterFactory(
79-
kotlinJsonMapper.asConverterFactory(
80-
"application/json; charset=UTF-8".toMediaType(),
81-
),
82-
)
83-
.client(configureOkHttpClient(OkHttpClient.Builder()).build())
84-
.baseUrl(LOCAL_HOST)
85-
.build()
85+
val okHttpClient by lazy { configureOkHttpClient(OkHttpClient.Builder()).build() }
8686

87-
val okHttpClient = configureOkHttpClient(OkHttpClient.Builder()).build()
87+
val retrofit: Retrofit by lazy {
88+
Retrofit
89+
.Builder()
90+
.addConverterFactory(
91+
kotlinJsonMapper.asConverterFactory(
92+
"application/json; charset=UTF-8".toMediaType(),
93+
),
94+
)
95+
.client(okHttpClient)
96+
.baseUrl(LOCAL_HOST)
97+
.build()
98+
}
8899
}

0 commit comments

Comments
 (0)