Untitled

Hilt에서는 표준 컴포넌트가 위 이미지 처럼 정의가 되어 있기 때문에 개발자기 직접 컴포넌트를 정의 하지는 않는다. 물론 커스텀 컴포넌트 정의 하는 방법은 존재하지만 일반적으로는 권장하진 않는다.

위 그림에서 화살표 방향은 하위 컴포넌트를 가르키는것이다.

그래서 SingletonComponent가 최상위 컴포넌트이다. 그리고 일반적으로 하위 컴포넌트는 상위 컴포넌트의 바인딩에 접근이 가능하다. 하지만 역방향으로 SingletonComponent가 ActivityComponent나 ViewWithFragmentComponent의 의존성에는 접근을 하지 못한다.

※ 의존 관계를 잘못 설정하였을 경우 메모리 누수가 있을수도 있으니 주의

컴포넌트의 생명주기

Component Scope Created at Destroyed at
SingletonComponent @Singleton Application#onCreate() Application#onDestroy()
ActivityRetainedComponent @ActivityRetainedScoped Activity#onCreate() Activity#onDestroy()
(화면 회전이 아닌 완전히 destroyed 되었을 때)
ViewModelComponent @ViewModelScoped ViewModel created ViewModel destroyed
ActivityComponent @ActivityScoped Activity#onCreate() Activity#onDestroy()
FragmentComponent @FragmentScoped Fragment#onAttach() Fragment#onDestroy()
ViewComponent @ViewScoped View#super() View destroyed
ViewWithFragmentComponent @ViewScoped View#super() in Fragment View destroyed
ServiceComponent @ServiceScoped Service#onCreate() Service#onDestroy()

Scope vs Unscope

// 이 바인딩은 매 요청시 새로운 인스턴스를 생성합니다.
class UnscopedBinding @inject constructor() {
}

// 이 바인딩은 스코프 애노테이션이 있으므로,
// 해당 Hilt 컴포넌트의 수명동안은 매 요청에 동일 인스턴스 반환을 보장한다.
@FragmentScoped
class ScopedBinding @Inject constructor() {
}

모듈 Scope 지정하기

@Module
@InstallIn(FragmentCompnent::class)
object FooModule {
@Provides
fun provideUnscopedBinding() = UnscopedBinding()

@Provides
@FragmentScoped
fun provideScopedBinding() = ScopedBinding()
}
// 서로 같음

Scope Annotation은

  1. 어떤 의존성을 인스턴스화하는 비용이 클 때
  2. 동일한 인스턴스를 반환을 원할때
  3. 특정 인스턴스를 공유 하고 싶을때