Retrofit in object form

Viewed 44

I have an MVVM program that uses Retrofit and Hilt
I have two questions:

  1. Why the most examples the Retrofit was created in object form instead of class form?
  2. 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()
}
1 Answers

Because, retrofit it self actually a class that generate retrofit instance (if you see, retrofit does not needed some context).

And no 2, if you have learned or reading about SOLID programming, you will know. then if you use it on AppModule, it will very difficult to maintain (just imagine your app will be have so much module and you put all of your module in app module)

Related