current position:Home>Android: a dependency injection framework
Android: a dependency injection framework
2022-01-26 23:50:19 【KEN】
This document is not authorized , Don't reprint
Preface
Work in Android It has been developed for more than two years , Access to different frames , From the very beginning ButterKnife
To the back Kotlin
have to Kotlin-android-extensions
, Here we are DataBinding
and ViewBinding
, One of the most impressive is not this kind of , It's not like that. RxJava2
This kind of , Instead, it relies on injection components such as Dagger2
, Come back later Koin
, And the latest Hilt
. So let's try to see if we can write a similar framework by hand .
Preliminary analysis
I have roughly analyzed several points that we need to solve :
One 、 Without reflection based on , How to save our pre initialized content , Or the object we want to initialize .
Two 、 Scope problem , I initialized it Module
The question of which scope to initialize , There is also a kind of global Module
.
3、 ... and 、 When our Module
Contains the life cycle of existence , Such as holding LifeOwnwer
Of Activity
, perhaps Fragment
And so on .
Start the first line of code
Preface
The project address is here Kinject Based on the framework of Kotlin developable , Apply to reified
,DSL
And other grammar and methods .
If you read my article Android Development : Share how to make good use of Kotlin Characteristics ( One )---- Improve development efficiency
I should be impressed. At the beginning, I talked about how to use Lazy Perform global initialization , At that time, it was the prototype of this project . If we want to inject into ViewModel What about the objects in , Need to be in Activity Use this Module
, From the third point we analyzed earlier , You need to monitor the lifecycle .
Analysis preparation
Then our first step should be to build a pool to hold these Module
, Well known , This pool we often use HashMap
,ArraryMap
And so on. KEY-VALUE
pool , I'm going to use ConcurrentHashMap
, For concurrency compatibility .
Let's define this first KEY
, First of all, this KEY
, What is needed , It's very simple. The only content , Make sure you get to the only content , Find the only answer . So there is the following :
open class Qualifier<D> {
private var key : D? = null
fun getKey() = key
fun setKeyName(key:D){
this.key = key
}
override fun hashCode(): Int {
return 31 * getKey().hashCode()
}
override fun equals(other: Any?): Boolean {
return if(other is Qualifier<*>){
other.key == this.key
}else{
false
}
}
override fun toString(): String {
return "Qualifier[Key:${key}]"
}
}
Copy code
Then we mainly use string as discrimination , Then it becomes :
class StringQualifier : Qualifier<String>()
Copy code
KEY
It's done , Then we have to decide VALUE
The content of , Obviously VALUE
It's ours Module
,
Actually Moduel
It's also very simple. , Is to save the object .
private val entrySingle by lazy { ConcurrentHashMap<String, Any>() }
private val entryFactory by lazy { ConcurrentHashMap<String, () -> Any?>() }
Copy code
Use two ConcurrentHashMap
, The first one is for certificates of deposit or , Initialize the content once , The second storage method , Then each call will re execute the method , All new objects are as follows :
The second step , Treatment of the life cycle
In fact, at this stage, we have basically completed most of the contents of the simple framework , The next step is just to manage the areas containing the life cycle , We just need to inherit LifecycleObserver
, Just remove what we store in the appropriate life cycle .
Practical application
This practical application is in another project of mine MaterialWanAndroid client Apply on , The core content is
initScope {
module(viewModel, lifeModule {
scopeLifeOwner(viewModel)
})
}
Copy code
stay Activity
In the ViewModel
object , Inject LifeOwner
, Then our warehouse XXXReposiory
Just call getLifeOwner
Method , as follows :
if(owner == null){
owner = getLifeOwner(viewModel)
owner?.lifecycle?.addObserver(this)
}
Copy code
Among them the viewModel
, Is that we are Activity Initialized in viewModel
.
ending
In fact, such a simple handwriting injection framework is still relatively simple , But it does satisfy most of the development Such as singleton Retorfit
Of Api
initScope {
single { Retorfit.create(Main::class.java) }
}
Copy code
Then in the warehouse, we just need , In this way, you can use , Databases work similarly
private val api : Main by single()
Copy code
copyright notice
author[KEN],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262350153488.html
The sidebar is recommended
- Spring IOC container loading process
- [thinking] the difference between singleton mode and static method - object-oriented programming
- Hadoop environment setup (MySQL environment configuration)
- 10 minutes, using node JS creates a real-time early warning system for bad weather!
- Git tool
- Force deduction algorithm - 92 Reverse linked list II
- What is the sub problem of dynamic programming?
- C / C + +: static keyword summary
- Idea does not have the artifacts option when configuring Tomcat
- Anaconda can't open it
guess what you like
-
I don't know how to start this
-
Matlab simulation of transportation optimization algorithm based on PSO
-
MySQL slow log optimization
-
[Vue] as the window is stretched (larger, smaller, wider and higher), the text will not be displayed
-
Popular Linux distributions for embedded computing
-
Suzhou computer research
-
After installing SSL Certificate in Windows + tomcat, the domain name request is not successful. Please answer!!
-
Implementation time output and greetings of jQuery instance
-
The 72 year old uncle became popular. Wu Jing and Guo fan made his story into a film, which made countless dreamers blush
-
How to save computer research
Random recommended
- Springboot implements excel import and export, which is easy to use, and poi can be thrown away
- The final examination subjects of a class are mathematical programming, and the scores are sorted and output from high to low
- Two pronged approach, Tsinghua Professor Pro code JDK and hotspot source code notes, one-time learning to understand
- C + + recursive knapsack problem
- The use of GIT and GitHub and the latest git tutorial are easy to understand -- Video notes of crazy God speaking
- PostgreSQL statement query
- Ignition database test
- Context didn't understand why he got a high salary?, Nginxfair principle
- Bootstrap switch switch control user's guide, springcloud actual combat video
- A list that contains only strings. What other search methods can be used except sequential search
- [matlab path planning] multi ant colony algorithm grid map path planning [including GUI source code 650]
- [matlab path planning] improved genetic algorithm grid map path planning [including source code phase 525]
- Iinternet network path management system
- Appium settings app is not running after 5000ms
- Reactnative foundation - 07 (background image, status bar, statusbar)
- Reactnative foundation - 04 (custom rpx)
- If you want an embedded database (H2, hsql or Derby), please put it on the classpath
- When using stm32g070 Hal library, if you want to write to flash, you must perform an erase. If you don't let it, you can't write continuously.
- Linux checks where the software is installed and what files are installed
- SQL statement fuzzy query and time interval filtering
- 69. Sqrt (x) (c + + problem solving version with vs runnable source program)
- Fresh students are about to graduate. Do you choose Java development or big data?
- Java project: OA management system (java + SSM + bootstrap + MySQL + JSP)
- Titanic passenger survival prediction
- Vectorization of deep learning formula
- Configuration and use of private image warehouse of microservice architect docker
- Relearn JavaScript events
- For someone, delete return 1 and return 0
- How does Java dynamically obtain what type of data is passed? It is used to judge whether the data is the same, dynamic data type
- How does the database cow optimize SQL?
- [data structure] chain structure of binary tree (pre order traversal) (middle order traversal) (post order traversal) (sequence traversal)
- Webpack packaging optimization solution
- 5. Operation element
- Detailed explanation of red and black trees
- redhat7. 9 install database 19C
- Blue Bridge Cup notes: (the given elements are not repeated) complete arrangement (arrangement cannot be repeated, arrangement can be repeated)
- Detailed explanation of springboot default package scanning mechanism and @ componentscan specified scanning path
- How to solve the run-time exception of test times
- Detailed explanation of k8s management tool kubectl
- Android system view memory command