💡 constructor inject ?
- 프로젝트 내에서 클래스의 인스턴스를 hilt에게 바로 제공할 수 있는 경우에는 constructor inject를 통해 종속성을 제공해줄 수 있음.
❗️room, retrofit과 같은 외부 라이브러리에서 제공되는 클래스처럼 프로젝트 내에서 소유할 수 없는 경우 hilt module을 추가하여 종속성을 제공할 수 있다.
💡 Binds ?
- @Binds는 constructor를 가질 수 없는 인터페이스에 대한 종속성 삽입의 경우에 사용함.
- 인터페이스 인스턴스를 제공한다.(인터페이스의 경우 바로 인스턴스를 생성할 수 없기 때문에)
// 인터페이스
interface LogRepository {
suspend fun add(msg: String)
suspend fun getLogs() : List<Log>
}
// 인터페이스 구현체
@Singleton
class LogDBRepository @Inject constructor(private val logDao: LogDao,
private val ioDispatcher : CoroutineDispatcher) : LogRepository {
override suspend fun add(msg: String) = withContext(ioDispatcher) {
logDao.add(Log(msg = msg))
}
override suspend fun getLogs(): List<Log> = withContext(ioDispatcher) {
logDao.getLogs()
}
}
@InstallIn(SingletonComponent::class)
@Module
abstract class LogDBModule {
@Binds
@Singleton
abstract fun bindLogDBRepository(impl: LogDBRepository) : LogRepository
}
💡 Provides ?
- 외부 라이브러리에서 제공되는 클래스로 Builder 패턴 등을 통해 인스턴스를 생성해야 하는 경우에 사용 함.
- 클래스의 인스턴스(소유하지 않은 클래스)를 제공한다.
@InstallIn(SingletonComponent::class)
@Module
object DBModule {
@Provides
@Singleton
fun provideDatabase(@ApplicationContext context: Context) : AppDatabase {
return Room.databaseBuilder(
context,
AppDatabase::class.java,
"logdata.db"
).build()
}
}
'안드로이드' 카테고리의 다른 글
[안드로이드] StateFlow 알아보기 (0) | 2022.10.19 |
---|---|
[안드로이드] mvvm 패턴 (0) | 2022.10.16 |
[안드로이드] Hilt - 1 (0) | 2022.10.13 |
[안드로이드] 코루틴 - Scope, Dispacher (0) | 2022.10.12 |
[코틀린] Paging3 (0) | 2022.10.10 |