@@ -15,7 +15,16 @@ import okhttp3.OkHttpClient
1515import okhttp3.logging.HttpLoggingInterceptor
1616import retrofit2.Retrofit
1717import 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
1928class 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