-
Hilt 공식문서 훑어보기1IT/android 2024. 12. 8. 20:00SMALL
Hilt Application
All apps using Hilt must contain an Application class annotated with @HiltAndroidApp. @HiltAndroidApp kicks off the code generation of the Hilt components and also generates a base class for your application that uses those generated components. Because the code generation needs access to all of your modules, the target that compiles your Application class also needs to have all of your Dagger modules in its transitive dependencies.
Just like other Hilt Android entry points, Applications are members injected as well. This means you can use injected fields in the Application after super.onCreate() has been called.
Hilt Application
모든 Hilt 를 사용하는 앱은 @HiltAndroidApp 어노테이션으로 표기된 Application class 를 포함하고 있어야 합니다. @HiltAndroidApp 어노테이션은 Hilt components 들의 코드생성의 시작점이고 application 클래스에 대한 base 클래스를 생성합니다. 이 base 클래스는 생성된 hilt components 들을 사용하게 됩니다. 코드 생성은 모든 모듈에 대한 접근을 필요로 하기 때문에, Application 클래스를 컴파일하는 모든 타겟 (보통 App 모듈이 되겠죠?) 은 모든 Dagger 모듈들에 접근할 수 있어야합니다. 다른 Hilt Android entry point 처럼 Application에도 멤버 인젝션이 동작합니다. 이것은 super.onCreate() 가 호출 된 이후에 삽입된 필드들을 사용할 수 있다는것을 의미합니다.
주의사항: onCreate()에서 모든 인젝트된 필드들이 동시에 생성되기 때문에, 특정 객체가 나중에 필요하거나 조건부로 필요한 경우 Provider를 사용하여 인젝션을 지연시킬 수 있습니다. 특히 앱 시작의 크리티컬 패스에 있는 Application 클래스에서는 불필요한 인젝션을 피하는 것이 성능상 중요할 수 있습니다.
// Hilt 사용 전 class MyApplication : MyBaseApplication() { @Inject lateinit var bar: Bar override fun onCreate() { super.onCreate() val myComponent = DaggerMyComponent .builder() ... .build() myComponent.inject(this) } } // Hilt 사용 후 @HiltAndroidApp class MyApplication : MyBaseApplication() { @Inject lateinit var bar: Bar override fun onCreate() { super.onCreate() // 인젝션은 super.onCreate()에서 발생 // bar 사용 가능 } }
위 처럼 @HiltAndroidApp 을 사용할 경우 Darrger 에 직접 inject 시켜야하는 불편함을 제거하고 자동으로 처리되게 할 수 있습니다.
@AndroidEntryPoint
Once you have enabled members injection in your Application, you can start enabling members injection in your other Android classes using the @AndroidEntryPoint annotation. You can use @AndroidEntryPoint on the following types:
AndroidEntryPoint
일단 Application 에서 멤버 인젝션을 허용했다면, 다른 안드로이드 class 에도 멤버 인젝션을 가능하게 할 수 있습니다 @AndroidEntryPoint 어노테이션을 활용함으로써요.
@AndroidEntryPoint 어노테이션은 다음과같은 타입에 사용할 수 있습니다:
1. Activity
2. Fragment
3. View
4. Service
5. BroadcastReceiver
주의사항: ViewModel은 별도의 API 인 @HiltViewModel 로 지원됩니다.
아래의 예는 @AndroidEntryPoint 어노테이션을 액티비티에 추가하는 예제인데요, 다른 타입들에도 마찬가지로 아래 예제와같은 절차를 거칩니다.
먼저 Activity 에 멤버 인젝션을 허용하기위해서 @AndroidEntryPoint 어노테이션을 Activity 클래스에 붙입니다.
@AndroidEntryPoint class MyActivity : MyBaseActivity() { @Inject lateinit var bar: Bar // Bindings in SingletonComponent or ActivityComponent override fun onCreate() { // Injection happens in super.onCreate(). super.onCreate() // Do something with bar ... } }
주의사항: Hilt는 현재 ComponentActivity 와 androidx library frament 를 상속한 fragment 에만 지원되고 있습니다. Android Platfrom 내의 Fragment 에는 적용되지않습니다. (Deprecated 됨)
Hilt Modules
Hilt modules are standard Dagger modules that have an additional @InstallIn annotation that determines which Hilt component(s) to install the module into.
When the Hilt components are generated, the modules annotated with @InstallIn will be installed into the corresponding component or subcomponent via @Component#modules or @Subcomponent#modules respectively. Just like in Dagger, installing a module into a component allows that binding to be accessed as a dependency of other bindings in that component or any child component(s) below it in the component hierarchy. They can also be accessed from the corresponding @AndroidEntryPoint classes. Being installed in a component also allows that binding to be scoped to that component.
Hilt Modules
Hilt 모듈은 표준 Dagger 모듈이고 이것은 @Installin 어노테이션을 달고있습니다. 이 어노테이션은 해당 모듈이 어떤 Hilt 컴포넌트에 설치될지를 지정합니다.
예제를 보면,// 싱글톤 스코프에 설치되는 모듈 @Module @InstallIn(SingletonComponent::class) object AppModule { @Provides @Singleton fun provideDatabase(): AppDatabase = // ... } // 액티비티 스코프에 설치되는 모듈 @Module @InstallIn(ActivityComponent::class) object ActivityModule { @Provides fun provideViewModel(): MyViewModel = // ... }
Hilt 컴포넌트들이 생성될때, @Installin 어노테이션을 가지는 모듈은 각각 component 또는 subcomponent 를 따라서 설치됩니다.
Dagger 에서 처럼, 모듈을 컴포넌트에 설치하면 해당 바인딩을 그 컴포넌트 내의 다른 바인딩들의 의존성으로 사용할수 있고, 컴포넌트 계층 구조상 그 아래에 있는 모든 자식 컴포넌트들 에서도 사용할 수 있습니다. 또한 @AndroidEntryPoint 클래스에서도 접근이 가능합니다. 컴포넌트에 설치된다는것은 해당 바인딩을 그 컴포넌트의 스코프로 설정한다는 의미입니다.
Using @InstallIn
A module is installed in a Hilt Component by annotating the module with the @InstallIn annotation. These annotations are required on all Dagger modules when using Hilt, but this check may be optionally disabled.
Using @InstallIn
모듈은 @InstallIn 어노테이션을 붙이는걸로 Hilt 컴포넌트에 설치됩니다. 이 어노테이션은 모든 Dagger 모듈에 필요합니다 Hilt를 사용할때. 하지만 이것을 체크하는것을 선택적으로 disable 시킬수가 있습니다.
@InstallIn 어노테이션 체크 로직이 기본적으로 enable 된 이유는, 만약에 개발자가 해당 어노테이션을 빼먹었을경우에 이것을 디버깅하기 매우 힘들 수 있다는 점 때문입니다.
LIST'IT > android' 카테고리의 다른 글
Gradle 훑어보기1 - 기본사항 (1) 2024.12.14 DoveLetter interview question 훑어보기1 (1) 2024.12.09 Hilt 공식문서 훑어보기2 Hilt Components (1) 2024.12.08 Hilt 이해를 위한 Dagger 기반지식 쌓기1 (2) 2024.12.08 Composable의 수명주기 (0) 2024.11.21