I have an MVVM program that uses Retrofit and Hilt
I have two questions:
- Why the most examples the Retrofit was created in object form instead of class form?
- Why we shouldn't implements (inheritance) the AppModule from Retrofit to make a limitation for accessing the Retrofit directly?
My personal experience leads me to write it that way, but I have never seen something like it. I want to know about expert programmers' opinions on problems in my suggested way.
Retrofit class:
open class BaseApi protected constructor(){
private fun createBuilder(baseUrl : String): Retrofit {
val okHttpClient = OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.build()
return Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
}
protected fun getWeatherService(): WeatherService {
val weatherServiceBaseAddress = "https://api.weatherapi.com/"
return createBuilder(weatherServiceBaseAddress).create(WeatherService::class.java)
}
}
AppModule:
@Module
@InstallIn(SingletonComponent::class)
class AppModule : BaseApi() {
@Singleton
@Provides
fun weatherServiceProvider() = getWeatherService()
}