@Module
@InstallIn(SingletonComponent::class)
object AppModule {
/*
@Singleton
TR -> Tüm uygulamada oluşturulan tek örnek kullanılacak bir daha instance oluşturmayacak ---silinebilir
EN -> The only instance created in the entire application will be used and will not create another instance ---can be deleted
*/
private var retrofitInstance: Retrofit? = null
private fun createRetrofitInstance(): Retrofit{
val okHttpClient = OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(1, TimeUnit.MINUTES)
.writeTimeout(1, TimeUnit.MINUTES)
.apply {
if (**Utils.isDeveloper**) { // Chuck On/Off Preference
addInterceptor(ChuckInterceptor(Utils.context))
}
}
.build()
return Retrofit.Builder()
.baseUrl(WebServiceUtils.generateBaseUrl())
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
}`
fun updateRetrofitInstance() {
retrofitInstance = createRetrofitInstance()
}
@Provides
fun provideRetrofitInstance(): Retrofit {
if (retrofitInstance == null) {
retrofitInstance = createRetrofitInstance()
}
return retrofitInstance!!
}
@Provides
fun provideTransactionService(retrofit: Retrofit): TransferRestInterface{
return retrofit.create(TransferRestInterface::class.java)
}
}
如何确保使用最新的Retrofit对象?
apply {
if (Utils.isDeveloper) { // Chuck On/Off Preference
addInterceptor(ChuckInterceptor(Utils.context))
}
}
在这部分中,我使用 SharedPreferences 检索 isDeveloper 的值。当应用程序运行时,直接创建Retrofit并检索isDeveloper的值。后来,即使在设置屏幕中更改 isDeveloper 值时更新了 Retrofit 对象,程序仍然使用之前的对象。
原因是当程序首次打开时,以下部分起作用:
@Provides
fun provideTransactionService(retrofit: Retrofit): TransferRestInterface{
return retrofit.create(TransferRestInterface::class.java)
}
之后即使Retrofit更新了,这部分也不再起作用了。
更改时使 Retrofit 实例无效
修改
updateRetrofitInstance
方法,将retrofitInstance
设置为null:
fun updateRetrofitInstance() {
retrofitInstance = null // Invalidate existing instance
createRetrofitInstance() // Create a new instance
}
每当 Utils 类中 updateRetrofitInstance
发生变化时,请调用
isDeveloper
。这可以通过回调机制或通过观察 SharedPreferences 中的变化来完成。