简体   繁体   中英

Singletons with lazy initialization vs singletons with Hilt annotations

Let's say I want to create an object that follows the Singleton pattern. I can do it in the following ways:

Method 1: Singleton using Lazy Initialization

@Singleton
object RetrofitCreator {
    val retrofitBuilder: Retrofit.Builder by lazy {
        Retrofit.Builder()
            .addConverterFactory(MoshiConverterFactory.create())
            .baseUrl("https://sample.com")
            .build()
            .create(ApiService::class.java)
    }
}

Method 2: Singleton with Hilt Annotations

@Module
@InstallIn(ApplicationComponent::class)
object RetrofitCreator {
    @Provides
    fun provideRetrofit(): Retrofit {
        return Retrofit.Builder()
                .baseUrl("https://sample.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
    }
}

What is the difference between the two methods I have shown? Is one of them better than the other? If so, which method and why?

Dependency Injection is something very different. Comparing using Singletons with lazy and Hilt is like comparing apples with oranges.

What is Lazy Initialization?

Lazy Initialization is when you want to create an object only when it is first used in the application. If the variable is never used, it will not create it to save memory and improve performance.

What is Dependency Injection?

Different classes often depend on other objects to work. Like ViewModels depend on repositories in order to fetch data (MVVM arch). The process of passing dependencies during initialization can be troublesome, especially later in the project if you want to change the implementation of the repository.

Dependency Injection makes your life easier by generating the boilerplate code behind the scenes to pass in the dependencies wherever required instead of you manually creating it.


In your example, there is no question of comparison between the two. If you are including Dagger Hilt in your project, you use the second way. If you aren't, then the first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM