当前位置:网站首页>Yyds dry inventory jetpack hit dependency injection framework Getting Started Guide
Yyds dry inventory jetpack hit dependency injection framework Getting Started Guide
2022-07-05 01:29:00 【Petterpx】

Hilt yes Google The latest dependency injection framework , It is based on Dagger Research and development , But it's different from Dagger. about Android For developers ,Hilt It can be said that it is specially for Android make , Provides a way to Dagger Dependency injection into Android Standard approach to applications , And created a standard set of components and scopes , These components are automatically integrated into Android Throughout the life cycle of the application , To make it easier for developers to get started .
Before learning this article , Suppose you already know what dependency injection is , If I don't know , You can understand the concept first .Hilt The aim is to reduce Android The developer's initial cost of using the dependency injection framework , But we still need to understand the basic idea .
Some corresponding notes are as follows :
@HiltAndroidApp
Trigger Hilt Code generation , Include base classes for applications , You can use dependency injection , The application container is the parent container of the application , This means that other containers can access the dependencies they provide .
@AndroidEntryPoint
It creates a dependent container , The container follows Android The life cycle of a class
@Inject
Fields used for Injection , Its type cannot be Private
If you want to tell Hilt How to provide instances of corresponding types , Need to put @Inject Add to the constructor of the class to be injected .
Hilt Information about how to provide different types of instances is also known as binding **.**
@Install(xx)
Install To tell Hilt Which component will this module be installed on .
Components (Compenent)
Hitl The following standard components are available by default , Just add... To the class
@AndroidEntryPointYou can support the injection of the following classes
| Compenent | Injector for |
|---|---|
ApplicationComponent | Application |
ActivityRetainedComponent | ViewModel( see also JetPack-ViewModel Expand ) |
ActivityComponent | Activity |
FragmentComponent | Fragment |
ViewComponent | View |
ViewWithFragmentComponent | View And @WithFragmentBindings |
ServiceComponent | Service |
It should be noted that ,Hilt Only extensions are supported FragmentActivity( Such as AppCompatActivity) Activities and extensions Jetpack Fragments of the library Fragment, Without support FragmentAndroid platform ( It has been abandoned ) Of fragment .
Components (Compenent) Life cycle of
- It limits the life cycle of binding in the scope of creating and generating components
- It indicates the appropriate values that can be injected with members .( for example : When @Inject Field is not null when )
| Component | Scope of action | Created at | Destroyed at |
|---|---|---|---|
ApplicationComponent | @Singleton | Application#onCreate() | Application#onDestroy() |
ActivityRetainedComponent | @ActivityRetainedScope | Activity#onCreate() 1 | Activity#onDestroy() 1 |
ActivityComponent | @ActivityScoped | Activity#onCreate() | Activity#onDestroy() |
FragmentComponent | @FragmentScoped | Fragment#onAttach() | Fragment#onDestroy() |
ViewComponent | @ViewScoped | View#super() | View destroyed |
ViewWithFragmentComponent | @ViewScoped | View#super() | View destroyed |
ServiceComponent | @ServiceScoped | Service#onCreate() | Service#onDestroy() |
By default , All bindings are scopeless , in other words , Every time you bind , Will create a new binding instance ;
however ,Dagger Allow binding scopes to specific components , As shown in the table above , Within the scope of the specified component , Instances are created only once , And all requests for the binding will share the same instance .
for example :
among @Singleton On behalf of TestComponent Instances throughout app Is the only one , When a subsequent class wants to inject it , Will share this instance .
How to use ?
Import dependencies first
Corresponding model Add... Below
Take up a :
We have a NetDataSource Of Remote data class , Then we may need to Activity Call in , The code is as follows
There's no problem with this , That's what we do most of the time , Of course. kt Can also be used in by lazy, But it depends on your own scene . But how to use the above code Hilt Transformation ?
After transformation
Is that the end , If used in this way , Then it will report the error directly , because Hilt All modules need to be accessed during code generation , So you have to use @HiltAndroidApp Label your base class Application. It's like this :
Again , Added @HiltAndroidApp after , You can also use... Anywhere in the future @ApplicationContext
@Module
The module is used to Hlit Add binding , let me put it another way , Is to tell Hlit How to provide different types of instances .
Added @Module Annotated classes , It represents quite a module , And tell which container can be installed with binding through the specified component .
about Hilt Every... That can be injected Android class , There's a connection Hilt Component, for example ,Application The container is associated with it ApplicationComponent , also Fragmenet The container is associated with FragmentComonent, This is the component life cycle we talked about at the beginning
Take up a :
Create a module :
Install To tell hilt Which component will this module be installed on .
A common misconception is , All bindings declared in a module will act on the component that installs the module . however , This is not the case . Binding declarations that use only scope annotations will be limited to scope .
When to add an injection range ?
Scoping a binding comes at a cost in terms of the size of the generated code and its runtime performance , Therefore, use scope with caution . The general rule for determining whether a binding should restrict scope is , Scope the binding only if the binding scope is required for code correctness . If you think the binding is scoped for performance reasons only , Please first verify whether there is a performance problem , Then consider using
@ReusableInstead of component scope .
Be careful : stay Kotlin in , Contains only @Provides The module of the function can be object class . such , The provider can be optimized , And it can almost be inlined in the generated code .
Use @Provides tell Hilt How to get specific examples
To tell Hilt How to provide types that cannot be injected by constructors
whenever Hilt When you need to provide an instance of this type , The body of the function that will execute the annotated function .@Provides Commonly used in modules
Take up a :
room General usage of
We use room, There is a database table and the corresponding Dao
next , We have one more AppDataBase and A single example of roomDatabase
Generally, when we use it , They are written as follows :
How to use it Hilt Transformation ?
We create a BookModule, And use @Model Note that this is a module ,@InstallIn Declare that the life scope of this module is APP Level
We are one of the provideBookDao Added @Provides, Its meaning is to tell Hilt Provide examples BookDao when , You need to perform database.bookDao(). Because we have AppDatabase Passing dependencies , So we also need to tell Hilt How to provide instances of this type .
because AppDatabase By Room Generated , So it's another class that the project doesn't own , Therefore, we can directly copy the original method , there @Singleton Flag whose method will only be called once , Similar to a single case .
change MainActivity The code in is as follows :
Up to now , Even if we finish the transformation , In this case , We can get this anywhere BookDao. And free from manual construction
Use @Binds Provide injection for the interface
For interfaces , Cannot inject using constructor , We need to tell Hilt Which implementation to use .Binds That's what it does .
Pay attention to the following service conditions :
- Binds Must annotate an abstract function , The return value of an abstract function is the interface we provide for its implementation . Specify the implementation by adding a unique parameter with an interface implementation type .
Take up a :
We have a IBook Interface , Used to store and query book data
Then, if we want to get the interface object elsewhere , The conventional implementation may be One of your concrete implementation classes implements its , And then where it needs to be used Again val iBook=xxxImpl()
If you use Hint Well ?, Continue the code demonstration
Then there is a concrete implementation class BookImpl , Here we use constructor Injection And injected BookDao Used to handle specific data storage . Here we use the suspend function , For students who are not familiar with this department , It can be understood as , It is equivalent to a marker bit , Prompt the compiler that there may be time-consuming operations , A suspend function is a logical process . For specific understanding, please refer to the explanation of big men such as throwing line , There's not much to explain here .
Then we need a new module , Used to implement IBook Interface Injection
In a certain Activity When using (Demo Example , In actual development, we prefer to put data processing in Repository in , from ViewModel management ):
Qualifiers( limit )
In the example above , There is only one concrete implementation class , But often actual development , We have multiple concrete implementations . And their scopes are different , Some may just be Activity Use , Some are used globally , How can we solve this problem ?
We can define different modules for two concrete implementations and use Qualifers Regulations .
Take up a :
Still with the above Code continuation . At this point, there is another implementation , Want to achieve storage with special conditions .
Another implementation class is :BookConditionImpl
And then we change BookModel, New in BookConditionModel modular
Then add two comments , Which USES @Qualifier
Then change our Activity
And JetPack
As Google Recommended dependency injection components , at present Hilt It can be done with ViewModel In combination with
Import dependence
Take up a
We create a MainActivty
ViewModel
TestRepository
Add -Java In the injection ViewModel
up to now ,Hilt The relevant content is basically over , For now Hilt There is less information about , And in alpha, If you want to use it in an actual project , It is recommended to try and read more documents , Make another decision .
Reference material , By Priority :
边栏推荐
- Global and Chinese market of veterinary thermometers 2022-2028: Research Report on technology, participants, trends, market size and share
- Database postragesq PAM authentication
- 【海浪建模2】三维海浪建模以及海浪发电机建模matlab仿真
- Discrete mathematics: propositional symbolization of predicate logic
- Call Huawei order service to verify the purchase token interface and return connection reset
- phpstrom设置函数注释说明
- Include rake tasks in Gems - including rake tasks in gems
- Introduction to the gtid mode of MySQL master-slave replication
- 无心剑英译席慕容《无怨的青春》
- JS implementation determines whether the point is within the polygon range
猜你喜欢

JS implementation determines whether the point is within the polygon range
![[untitled]](/img/d1/85550f58ce47e3609abe838b58c79e.jpg)
[untitled]

The perfect car for successful people: BMW X7! Superior performance, excellent comfort and safety

【大型电商项目开发】性能压测-性能监控-堆内存与垃圾回收-39

Redis(1)之Redis简介

Senior Test / development programmers write no bugs? Qualifications (shackles) don't be afraid of mistakes

Armv8-a programming guide MMU (3)

Wechat applet; Gibberish generator

"2022" is a must know web security interview question for job hopping

Arbitrum: two-dimensional cost
随机推荐
[FPGA tutorial case 9] design and implementation of clock manager based on vivado core
MySQL REGEXP:正则表达式查询
Take you ten days to easily complete the go micro service series (IX. link tracking)
微信小程序:微群人脉微信小程序源码下载全新社群系统优化版支持代理会员系统功能超高收益
Pandora IOT development board learning (RT thread) - Experiment 4 buzzer + motor experiment [key external interrupt] (learning notes)
Wechat applet: Xingxiu UI v1.5 WordPress system information resources blog download applet wechat QQ dual end source code support WordPress secondary classification loading animation optimization
Database postragesql client connection default
A simple SSO unified login design
当产业互联网时代真正发展完善之后,将会在每一个场景见证巨头的诞生
Can financial products be redeemed in advance?
What is the current situation and Prospect of the software testing industry in 2022?
Database postragesq role membership
Database postragesq peer authentication
How to use words to describe breaking change in Spartacus UI of SAP e-commerce cloud
Hand drawn video website
【微处理器】基于FPGA的微处理器VHDL开发
实战模拟│JWT 登录认证
增量备份 ?db full
流批一体在京东的探索与实践
Express routing, express middleware, using express write interface