Android (안드로이드)/Hilt
Android in A..Z - Hilt (Component)
강태종
2021. 3. 18. 05:35
Hilt Component
삽입을 실행할 때 @InstallIn 주석을 사용하여 참조할 수 있는 구성요소를 설정하고 구성요소에 맞는 대상에서만 삽입할 수 있다.
Hilt Component | 인젝터 대상 |
ApplicationComponent | Application |
ActivityRetainedComponent | ViewModel |
ActivityComponent | Activity |
FragmentComponent | Fragment |
ViewComponent | View |
ViewWithFragmentComponent | @WithFragmentBindings 주석이 지정된 View |
ServiceComponent | Service |
Hilt Component Lifetimes
Hilt는 Hilt Component별 Android Class의 수명 주기에 따라 자동으로 생성되고 제거됩니다.
Hilt Component | 생성 위치 | 제거 위치 |
ApplicationComponent | Application#onCreate() | Application#onDestroy() |
ActivityRetainedComponent | Activity#onCreate() | Activity#onDestroy() |
ActivityComponent | Activity#onCreate() | Activity#onDestroy() |
FragmentComponent | Fragment#onAttach() | Fragment#onDestroy() |
ViewComponent | View#super() | 제거된 뷰 |
ViewWithFragmentComponent | View#super() | 제거된 뷰 |
ServiceComponent | Service#onCreate() | Service#onDestroy() |
Hilt Component Scope
기본적으로 Hilt에 Scope가 지정되지 않습니다. 즉 Inject를 요구할 때마다 새로운 인스턴스를 만들어서 Inject합니다.
하지만 상황에 따라 하나의 인스턴스를 공유해야 할 경우가 생깁니다. Scope를 설정하면 Scope에 해당하는 범위에서는 하나의 인스턴스를 공유합니다.
Android Class | Hilt Component | 범위 |
Application | ApplicationComponent | @Singleton |
View Model | ActivityRetainedComponent | @ActivityRetainedScope |
Activity | ActivityComponent | @ActivityScoped |
Fragment | FragmentComponent | @FragmentScoped |
View | ViewComponent | @ViewScoped |
@WithFragmentBindings 주석이 지정된 View | ViewWithFragmentComponent | @ViewScoped |
Service | ServiceComponent | @ServiceScoped |
Component 계층 구조
구성요소에 모듈을 설치하면 이 구성요소의 다른 결합 또는 구성요소 계층 구조에서 그 아래에 있는 하위 구성요소의 다른 결합의 종속 항목으로 설치된 모듈의 결합에 액세스할 수 있습니다.
Git (예제코드)
github.com/KangTaeJong98/Example/tree/main/Android/Hilt
KangTaeJong98/Example
My Example Code. Contribute to KangTaeJong98/Example development by creating an account on GitHub.
github.com