当前位置:网站首页>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 :
边栏推荐
- batchnorm. Py this file single GPU operation error solution
- [wave modeling 3] three dimensional random real wave modeling and wave generator modeling matlab simulation
- Discrete mathematics: Main Normal Form (main disjunctive normal form, main conjunctive normal form)
- Research Report on the overall scale, major producers, major regions, products and application segmentation of agricultural automatic steering system in the global market in 2022
- Yyds dry goods inventory [Gan Di's one week summary: the most complete and detailed in the whole network]; detailed explanation of MySQL index data structure and index optimization; remember collectio
- Poap: the adoption entrance of NFT?
- 【海浪建模3】三维随机真实海浪建模以及海浪发电机建模matlab仿真
- Wechat applet: the latest WordPress black gold wallpaper wechat applet two open repair version source code download support traffic main revenue
- [CTF] AWDP summary (WEB)
- 【FPGA教程案例9】基于vivado核的时钟管理器设计与实现
猜你喜欢
Logstash、Fluentd、Fluent Bit、Vector? How to choose the appropriate open source log collector
[OpenGL learning notes 8] texture
Grabbing and sorting out external articles -- status bar [4]
Complex, complicated and numerous: illustration of seven types of code coupling
[untitled]
【海浪建模2】三维海浪建模以及海浪发电机建模matlab仿真
Hedhat firewall
【海浪建模1】海浪建模的理论分析和matlab仿真
[wave modeling 3] three dimensional random real wave modeling and wave generator modeling matlab simulation
Wechat applet; Gibberish generator
随机推荐
[FPGA tutorial case 9] design and implementation of clock manager based on vivado core
Can financial products be redeemed in advance?
無心劍英譯席慕容《無怨的青春》
Express routing, express middleware, using express write interface
Exploration and Practice of Stream Batch Integration in JD
Nebula Importer 数据导入实践
Chia Tai International Futures: what is the master account and how to open it?
[untitled]
[development of large e-commerce projects] performance pressure test - Optimization - impact of middleware on performance -40
微信小程序;胡言乱语生成器
The perfect car for successful people: BMW X7! Superior performance, excellent comfort and safety
流批一体在京东的探索与实践
实战模拟│JWT 登录认证
【海浪建模2】三维海浪建模以及海浪发电机建模matlab仿真
Global and Chinese market of optical densitometers 2022-2028: Research Report on technology, participants, trends, market size and share
Es uses collapsebuilder to de duplicate and return only a certain field
微信小程序:星宿UI V1.5 wordpress系统资讯资源博客下载小程序微信QQ双端源码支持wordpress二级分类 加载动画优化
Redis(1)之Redis简介
增量备份 ?db full
【大型电商项目开发】性能压测-性能监控-堆内存与垃圾回收-39