SlideShare a Scribd company logo
1 of 1
Download to read offline
@HiltAndroidApp
Kicks off Hilt code generation.
Must annotate the Application class.
@HiltAndroidApp
class MyApplication : Application() { ... }
@AndroidEntryPoint *
Adds a DI container to the Android
class annotated with it.
@AndroidEntryPoint
class MyActivity : AppCompatActivity() { ... }
@ViewModelInject **
Tells Hilt how to provide instances of an
Architecture Component ViewModel.
class MyViewModel @ViewModelInject constructor(
private val adapter: AnalyticsAdapter,
@Assisted private val state: SavedStateHandle
): ViewModel() { ... }
Constructor Injection. Tells which
constructor to use to provide instances
and which dependencies the type has.
class AnalyticsAdapter @Inject constructor(
private val service: AnalyticsService
) { ... }
Field injection. Populates fields in
@AndroidEntryPoint annotated classes.
Fields cannot be private.
@AndroidEntryPoint
class MyActivity : AppCompatActivity() {
@Inject lateinit var adapter: AnalyticsAdapter
...
}
@Inject
@Module
Class in which you can add bindings for
types that cannot be constructor injected.
@InstallIn(ApplicationComponent::class)
@Module
class AnalyticsModule { ... }
@InstallIn
Indicates in which Hilt-generated DI
containers (ApplicationComponent in the
code) module bindings must be available.
@InstallIn(ApplicationComponent::class)
@Module
class AnalyticsModule { ... }
@Binds
Shorthand for binding an interface type:
- Methods must be in a module.
- @Binds annotated methods must be
abstract.
- Return type is the binding type.
- Parameter is the implementation type.
@InstallIn(ApplicationComponent::class)
@Module
abstract class AnalyticsModule {
@Binds
abstract fun bindsAnalyticsService(
analyticsServiceImpl: AnalyticsServiceImpl
): AnalyticsService
}
@Provides
Adds a binding for a type that cannot be
constructor injected:
- Return type is the binding type.
- Parameters are dependencies.
- Every time an instance is needed, the
function body is executed if the type is
not scoped.
@InstallIn(ApplicationComponent::class)
@Module
class AnalyticsModule {
@Provides
fun providesAnalyticsService(
converterFactory: GsonConverterFactory
): AnalyticsService {
return Retrofit.Builder()
.baseUrl("https://example.com")
.addConverterFactory(converterFactory)
.build()
.create(AnalyticsService::class.java)
}
}
Scope Annotations:
@Singleton
@ActivityScoped
…
Scoping object to a container.
The same instance of a type will be
provided by a container when using that
type as a dependency, for field injection,
or when needed by containers below in
the hierarchy.
@Singleton
class AnalyticsAdapter @Inject constructor(
private val service: AnalyticsService
) { ... }
Qualifiers for
predefined Bindings:
@ApplicationContext
@ActivityContext
Predefined bindings you can use as
dependencies in the corresponding
container.
These are qualifier annotations.
@Singleton
class AnalyticsAdapter @Inject constructor(
@ApplicationContext val context: Context
private val service: AnalyticsService
) { ... }
@Entry Point
Obtain dependencies in classes that are
either not supported directly by Hilt or
cannot use Hilt.
The interface annotated with @EntryPoint
must also be annotated with @InstallIn
passing in the Hilt predefined component
from which that dependency is taken
from.
Access the bindings using the appropriate
static method from EntryPointAccessors
passing in an instance of the class with
the DI container (which matches the value
in the @InstallIn annotation) and the entry
point interface class.
class MyContentProvider(): ContentProvider {
@InstallIn(ApplicationComponent::class)
@EntryPoint
interface MyContentProviderEntryPoint {
fun analyticsService(): AnalyticsService
}
override fun query(...): Cursor {
val appContext =
context?.applicationContext
?: throw IllegalStateException()
val entryPoint =
EntryPointAccessors.fromApplication(
appContext,
MyContentProviderEntryPoint::class.java)
val analyticsService =
entryPoint.analyticsService()
...
}
}
For more information about DI, Hilt and Dagger: https://d.android.com/dependency-injection
* The code example for this annotation assumes you’re using the Gradle plugin ** This annotation is avaiable using the androidx.hilt.hilt-lifecycle-viewmodel library
Annotation Usage Code Sample
Hilt & Dagger Annotations
v1.0 - @AndroidDev

More Related Content

What's hot

Creating custom Validators on Reactive Forms using Angular 6
Creating custom Validators on Reactive Forms using Angular 6Creating custom Validators on Reactive Forms using Angular 6
Creating custom Validators on Reactive Forms using Angular 6AIMDek Technologies
 
Introduction to Google Guice
Introduction to Google GuiceIntroduction to Google Guice
Introduction to Google GuiceKnoldus Inc.
 
VIPER Architecture
VIPER ArchitectureVIPER Architecture
VIPER ArchitectureAhmed Lotfy
 
20200815 inversions
20200815 inversions20200815 inversions
20200815 inversionsChiwon Song
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desaijinaldesailive
 
Interfaces Not Required — RubyHACK 2018
Interfaces Not Required — RubyHACK 2018Interfaces Not Required — RubyHACK 2018
Interfaces Not Required — RubyHACK 2018James Thompson
 
Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basicsRavindra K
 
Introduction to Zend Framework
Introduction to Zend FrameworkIntroduction to Zend Framework
Introduction to Zend FrameworkJamie Hurst
 
Beginner’s tutorial (part 1) integrate redux form in react native application
Beginner’s tutorial (part 1) integrate redux form in react native applicationBeginner’s tutorial (part 1) integrate redux form in react native application
Beginner’s tutorial (part 1) integrate redux form in react native applicationKaty Slemon
 
How to build integrated, professional enterprise-grade cross-platform mobile ...
How to build integrated, professional enterprise-grade cross-platform mobile ...How to build integrated, professional enterprise-grade cross-platform mobile ...
How to build integrated, professional enterprise-grade cross-platform mobile ...Appear
 
Design functional solutions in Java, a practical example
Design functional solutions in Java, a practical exampleDesign functional solutions in Java, a practical example
Design functional solutions in Java, a practical exampleMarian Wamsiedel
 
Dependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functionalDependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functionalMarian Wamsiedel
 
Creating EPiServer Usage Reports
Creating EPiServer Usage ReportsCreating EPiServer Usage Reports
Creating EPiServer Usage ReportsPaul Graham
 
Android DevConference - Android Clean Architecture
Android DevConference - Android Clean ArchitectureAndroid DevConference - Android Clean Architecture
Android DevConference - Android Clean ArchitectureiMasters
 
Introduction to the integral framework
Introduction to the integral frameworkIntroduction to the integral framework
Introduction to the integral frameworkKarthik Subramanian
 

What's hot (20)

Creating custom Validators on Reactive Forms using Angular 6
Creating custom Validators on Reactive Forms using Angular 6Creating custom Validators on Reactive Forms using Angular 6
Creating custom Validators on Reactive Forms using Angular 6
 
Introduction to Google Guice
Introduction to Google GuiceIntroduction to Google Guice
Introduction to Google Guice
 
VIPER Architecture
VIPER ArchitectureVIPER Architecture
VIPER Architecture
 
20200815 inversions
20200815 inversions20200815 inversions
20200815 inversions
 
Google Guice
Google GuiceGoogle Guice
Google Guice
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
 
List Views
List ViewsList Views
List Views
 
Interfaces Not Required — RubyHACK 2018
Interfaces Not Required — RubyHACK 2018Interfaces Not Required — RubyHACK 2018
Interfaces Not Required — RubyHACK 2018
 
Angular modules in depth
Angular modules in depthAngular modules in depth
Angular modules in depth
 
Angular 8
Angular 8 Angular 8
Angular 8
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
 
Introduction to Zend Framework
Introduction to Zend FrameworkIntroduction to Zend Framework
Introduction to Zend Framework
 
Ui 5
Ui   5Ui   5
Ui 5
 
Beginner’s tutorial (part 1) integrate redux form in react native application
Beginner’s tutorial (part 1) integrate redux form in react native applicationBeginner’s tutorial (part 1) integrate redux form in react native application
Beginner’s tutorial (part 1) integrate redux form in react native application
 
How to build integrated, professional enterprise-grade cross-platform mobile ...
How to build integrated, professional enterprise-grade cross-platform mobile ...How to build integrated, professional enterprise-grade cross-platform mobile ...
How to build integrated, professional enterprise-grade cross-platform mobile ...
 
Design functional solutions in Java, a practical example
Design functional solutions in Java, a practical exampleDesign functional solutions in Java, a practical example
Design functional solutions in Java, a practical example
 
Dependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functionalDependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functional
 
Creating EPiServer Usage Reports
Creating EPiServer Usage ReportsCreating EPiServer Usage Reports
Creating EPiServer Usage Reports
 
Android DevConference - Android Clean Architecture
Android DevConference - Android Clean ArchitectureAndroid DevConference - Android Clean Architecture
Android DevConference - Android Clean Architecture
 
Introduction to the integral framework
Introduction to the integral frameworkIntroduction to the integral framework
Introduction to the integral framework
 

Similar to Hilt Annotations

Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized projectFabio Collini
 
Android architecture
Android architecture Android architecture
Android architecture Trong-An Bui
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014First Tuesday Bergen
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDiego Lewin
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objectsSandeep Chawla
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVCRichard Paul
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 
Replicating production on your laptop using the magic of containers
Replicating production on your laptop using the magic of containersReplicating production on your laptop using the magic of containers
Replicating production on your laptop using the magic of containersJamie Coleman
 
Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributessonia merchant
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionDinesh Sharma
 
Replicating production on your laptop using the magic of containers v2
Replicating production on your laptop using the magic of containers v2Replicating production on your laptop using the magic of containers v2
Replicating production on your laptop using the magic of containers v2Jamie Coleman
 
Creating web api and consuming- part 1
Creating web api and consuming- part 1Creating web api and consuming- part 1
Creating web api and consuming- part 1Dipendra Shekhawat
 
Dependency injection: koin vs dagger
Dependency injection: koin vs daggerDependency injection: koin vs dagger
Dependency injection: koin vs daggerMatteo Pasotti
 
Murach: How to transfer data from controllers
Murach: How to transfer data from controllersMurach: How to transfer data from controllers
Murach: How to transfer data from controllersMahmoudOHassouna
 
Angularjs2 presentation
Angularjs2 presentationAngularjs2 presentation
Angularjs2 presentationdharisk
 

Similar to Hilt Annotations (20)

Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized project
 
Android architecture
Android architecture Android architecture
Android architecture
 
Dependency Injection for Android
Dependency Injection for AndroidDependency Injection for Android
Dependency Injection for Android
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
 
Di code steps
Di code stepsDi code steps
Di code steps
 
Modern android development
Modern android developmentModern android development
Modern android development
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
Cheat-sheet_Koin_2023.pdf
Cheat-sheet_Koin_2023.pdfCheat-sheet_Koin_2023.pdf
Cheat-sheet_Koin_2023.pdf
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
Replicating production on your laptop using the magic of containers
Replicating production on your laptop using the magic of containersReplicating production on your laptop using the magic of containers
Replicating production on your laptop using the magic of containers
 
Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributes
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency Injection
 
Replicating production on your laptop using the magic of containers v2
Replicating production on your laptop using the magic of containers v2Replicating production on your laptop using the magic of containers v2
Replicating production on your laptop using the magic of containers v2
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Creating web api and consuming- part 1
Creating web api and consuming- part 1Creating web api and consuming- part 1
Creating web api and consuming- part 1
 
Dependency injection: koin vs dagger
Dependency injection: koin vs daggerDependency injection: koin vs dagger
Dependency injection: koin vs dagger
 
Murach: How to transfer data from controllers
Murach: How to transfer data from controllersMurach: How to transfer data from controllers
Murach: How to transfer data from controllers
 
Angularjs2 presentation
Angularjs2 presentationAngularjs2 presentation
Angularjs2 presentation
 

Recently uploaded

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 

Recently uploaded (20)

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 

Hilt Annotations

  • 1. @HiltAndroidApp Kicks off Hilt code generation. Must annotate the Application class. @HiltAndroidApp class MyApplication : Application() { ... } @AndroidEntryPoint * Adds a DI container to the Android class annotated with it. @AndroidEntryPoint class MyActivity : AppCompatActivity() { ... } @ViewModelInject ** Tells Hilt how to provide instances of an Architecture Component ViewModel. class MyViewModel @ViewModelInject constructor( private val adapter: AnalyticsAdapter, @Assisted private val state: SavedStateHandle ): ViewModel() { ... } Constructor Injection. Tells which constructor to use to provide instances and which dependencies the type has. class AnalyticsAdapter @Inject constructor( private val service: AnalyticsService ) { ... } Field injection. Populates fields in @AndroidEntryPoint annotated classes. Fields cannot be private. @AndroidEntryPoint class MyActivity : AppCompatActivity() { @Inject lateinit var adapter: AnalyticsAdapter ... } @Inject @Module Class in which you can add bindings for types that cannot be constructor injected. @InstallIn(ApplicationComponent::class) @Module class AnalyticsModule { ... } @InstallIn Indicates in which Hilt-generated DI containers (ApplicationComponent in the code) module bindings must be available. @InstallIn(ApplicationComponent::class) @Module class AnalyticsModule { ... } @Binds Shorthand for binding an interface type: - Methods must be in a module. - @Binds annotated methods must be abstract. - Return type is the binding type. - Parameter is the implementation type. @InstallIn(ApplicationComponent::class) @Module abstract class AnalyticsModule { @Binds abstract fun bindsAnalyticsService( analyticsServiceImpl: AnalyticsServiceImpl ): AnalyticsService } @Provides Adds a binding for a type that cannot be constructor injected: - Return type is the binding type. - Parameters are dependencies. - Every time an instance is needed, the function body is executed if the type is not scoped. @InstallIn(ApplicationComponent::class) @Module class AnalyticsModule { @Provides fun providesAnalyticsService( converterFactory: GsonConverterFactory ): AnalyticsService { return Retrofit.Builder() .baseUrl("https://example.com") .addConverterFactory(converterFactory) .build() .create(AnalyticsService::class.java) } } Scope Annotations: @Singleton @ActivityScoped … Scoping object to a container. The same instance of a type will be provided by a container when using that type as a dependency, for field injection, or when needed by containers below in the hierarchy. @Singleton class AnalyticsAdapter @Inject constructor( private val service: AnalyticsService ) { ... } Qualifiers for predefined Bindings: @ApplicationContext @ActivityContext Predefined bindings you can use as dependencies in the corresponding container. These are qualifier annotations. @Singleton class AnalyticsAdapter @Inject constructor( @ApplicationContext val context: Context private val service: AnalyticsService ) { ... } @Entry Point Obtain dependencies in classes that are either not supported directly by Hilt or cannot use Hilt. The interface annotated with @EntryPoint must also be annotated with @InstallIn passing in the Hilt predefined component from which that dependency is taken from. Access the bindings using the appropriate static method from EntryPointAccessors passing in an instance of the class with the DI container (which matches the value in the @InstallIn annotation) and the entry point interface class. class MyContentProvider(): ContentProvider { @InstallIn(ApplicationComponent::class) @EntryPoint interface MyContentProviderEntryPoint { fun analyticsService(): AnalyticsService } override fun query(...): Cursor { val appContext = context?.applicationContext ?: throw IllegalStateException() val entryPoint = EntryPointAccessors.fromApplication( appContext, MyContentProviderEntryPoint::class.java) val analyticsService = entryPoint.analyticsService() ... } } For more information about DI, Hilt and Dagger: https://d.android.com/dependency-injection * The code example for this annotation assumes you’re using the Gradle plugin ** This annotation is avaiable using the androidx.hilt.hilt-lifecycle-viewmodel library Annotation Usage Code Sample Hilt & Dagger Annotations v1.0 - @AndroidDev