2

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()
}
Ali Doran
  • 378
  • 1
  • 12

1 Answers1

0

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)

Hadisyah
  • 34
  • 4
  • About your answer 1) There isn't any reason for don't use class for factory pattern classes. 2) I read SOLID before, but it is not my way. It's Hilt's suggestion to implement DB and Network on the AppModule. My question related to inheritance, It's not about AppModule – Ali Doran Jul 31 '22 at 11:52
  • 1. You will be get some difficult if using a common class because it's need declaration. 2. The module of hilt meant to be an dependency so if you want to inject it on any class, you no need to create the instance of class again and again, so it should be globally added as a module. – Hadisyah Jul 31 '22 at 12:01
  • The expetation of the module is have some singleton inside. so if you inject a module, it means the you also add these singleton. – Hadisyah Jul 31 '22 at 12:08