Kotlin/안드로이드 공부
Hilt @Provides vs @Binds
yerintil
2022. 6. 10. 13:23
728x90
어떻게 이렇게 할 때마다 찾아보는지... 내가 쓴 글로 한 번 정리를 해둬야겠다.
가장 큰 차이점은 @Binds 는 인터페이스를 제공하고, @Provides 는 클래스 인스턴스를 제공한다는 것이다.
@Binds
@Module
@InstallIn(SingletonComponent::class)
abstract class ServiceModule {
@Binds
@Singleton
abstract fun provideServiceHelper(threeServiceHelper: ThreeServiceHelper): ServiceHelper
}
인터페이스를 제공하는 경우 바로 인스턴스를 생성할 수 없기 때문에 실제 사용되는 구현을 Hilt 에게 알려준다.
@Provides
@Module
@InstallIn(ActivityComponent::class)
object AppModule {
@Provides
fun provideRetrofitService(): RetrofitService {
return Retrofit.Builder()
.baseUrl("https://3edc.tistory.com/")
.build()
.create(RetrofitService::class.java)
}
}
Retrofit 이나 Room 처럼 외부 라이브러리에서 제공되어 클래스를 소유하지 않은 경우, 빌드 패턴 등의 인스턴스를 생성해야 하는 경우 사용한다.