Android/Android
[Android][@Qualifier] Dagger Hilt로 같은 Retrofit 객체를 여러 번 호출할 때 사용하는 방법
로구상
2021. 8. 27. 18:54
반응형
Dagger Hilt로 Retrofit 모듈을 작성할 때 여러 개의 URL을 처리해야 하는 경우가 있다. 만약 그냥 작성하게 되면 다음과 같은 오류를 출력한다.
error: [Dagger/DuplicateBindings] retrofit2.Retrofit is bound multiple times:
이는 모듈 내의 각 메서드에서 같은 Retrofit 객체를 호출하고 있다는 에러이다(Hilt가 어떤 메서드의 Retrofit 객체를 사용해야 하는지 모름).
이를 해결하기 위해선 @Qualifier를 사용하여 annotation 클래스를 사용하면 된다.
사용법은 다음과 같다.
// AppMoudle.kt
@Module
@InstallIn(SingletonComponent::class)
object AppMoudle {
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class type1
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class type2
@Singleton
@Provides
@type1
fun provideType1(
@type1 retrofit: Retrofit
): TypeInstance1 =
retrofit.create(TypeInstance1::class.java)
@Singleton
@Provides
@type1
fun provideGetType1(): Retrofit =
Retrofit.Builder()
.baseUrl(baseTypeURL1)
.addConverterFactory(GsonConverterFactory.create())
.build()
@Singleton
@Provides
@type2
fun provideType2(
@type2 retrofit: Retrofit
): TypeInstance2 =
retrofit.create(TypeInstance2::class.java)
@Singleton
@Provides
@type2
fun provideGetType2(): Retrofit =
Retrofit.Builder()
.baseUrl(baseTypeURL2)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
// MainActivityRepository.kt
class MainActivityRepository @Inject constructor(
@AppModule.type2 private val typeInstance2: TypeInstance2
)
Retrofit 뿐만 아니라 다른 Module을 작성할 때도 위와 같이 작성하면 된다.
반응형