SlideShare ist ein Scribd-Unternehmen logo
1 von 1
Downloaden Sie, um offline zu lesen
@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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 

Kürzlich hochgeladen (20)

Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 

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