当前位置:网站首页>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
@AndroidEntryPoint
You 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 Fragment
Android 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
@Reusable
Instead 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 :
边栏推荐
- Heartless sword English translation of Xi Murong's youth without complaint
- [swagger]-swagger learning
- 107. Some details of SAP ui5 overflow toolbar container control and resize event processing
- Incremental backup? db full
- Analysis and comparison of leetcode weekly race + acwing weekly race (t4/t3)
- La jeunesse sans rancune de Xi Murong
- Nebula Importer 数据导入实践
- 微信小程序:独立后台带分销功能月老办事处交友盲盒
- JS implementation determines whether the point is within the polygon range
- [wave modeling 1] theoretical analysis and MATLAB simulation of wave modeling
猜你喜欢
Nebula importer data import practice
MySQL REGEXP:正则表达式查询
Roads and routes -- dfs+topsort+dijkstra+ mapping
Expansion operator: the family is so separated
Talking about JVM 4: class loading mechanism
phpstrom设置函数注释说明
【CTF】AWDP总结(Web)
BGP comprehensive experiment
Wechat applet: independent background with distribution function, Yuelao office blind box for making friends
Wechat applet: exclusive applet version of the whole network, independent wechat community contacts
随机推荐
MySQL REGEXP:正则表达式查询
無心劍英譯席慕容《無怨的青春》
【纯音听力测试】基于MATLAB的纯音听力测试系统
Wechat applet; Gibberish generator
Grabbing and sorting out external articles -- status bar [4]
How to use words to describe breaking change in Spartacus UI of SAP e-commerce cloud
Yyds dry goods inventory kubernetes management business configuration methods? (08)
Global and Chinese market of veterinary thermometers 2022-2028: Research Report on technology, participants, trends, market size and share
MySQL regexp: Regular Expression Query
【LeetCode】88. Merge two ordered arrays
Wechat applet: wechat applet source code download new community system optimized version support agent member system function super high income
Great God developed the new H5 version of arXiv, saying goodbye to formula typography errors in one step, and mobile phones can also easily read literature
Digital DP template
Four pits in reentrantlock!
Are you still writing the TS type code
微信小程序:独立后台带分销功能月老办事处交友盲盒
The performance of major mainstream programming languages is PK, and the results are unexpected
Complex, complicated and numerous: illustration of seven types of code coupling
"2022" is a must know web security interview question for job hopping
What is the current situation and Prospect of the software testing industry in 2022?