Junior — Middle
How can you implement a custom component in Hilt for dependency injection?
sobes.tech AI
Answer from AI
To create your own component in Hilt, you need to:
- Define an interface for the component, annotated with
@DefineComponent. It specifies dependencies available within the component. - Create an annotation to bind the component to a lifecycle, using
@DefineComponent.Builderand@Component.Builder. - Link the created component with an existing Hilt component using
@DefineComponent(parent = ...), specifying the parent component. - Create an annotation for dependency injection into this component using
@EntryPointor@InstallIn(YourCustomComponent.class).
Example:
@DefineComponent(parent = SingletonComponent::class)
interface CustomComponent
@DefineComponent.Builder
interface CustomComponentBuilder {
fun build(): CustomComponent
}
@InstallIn(CustomComponent::class)
@Module
class CustomModule {
@Provides
fun provideSomething(): Something = Something()
}
This way, you can create custom components with the desired scope and manage dependencies more flexibly.