开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 12 天,点击查看活动详情
之前给大家讲了一系列的dagger2,大家应该对dagger有一个简单的认知了,可能在实际使用中还会出现一些复杂的问题,再后面的项目中如果遇到了,到时候再作为单独的知识点来分享吧。今天想给大家再讲一个和注入相关的东西,那就是Hilt,可能大家想已经有dagger了为什么还要hilt,dagger其实已经很好用了,但是对于android的框架的东西还是有点水土不服,用起来也比较麻烦,所以才有了后来的hilt,hilt是专门针对android项目使用的,它的使用比dagger简单,能够很快的入门。今天就先简单的讲讲如何在android项目中使用hilt。
- 依赖
插件依赖:
首先在项目的build.gradle里面添加:
classpath 'com.google.dagger:hilt-android-gradle-plugin:2.42'
然后再app的build.gradle的头部加入插件:
id 'dagger.hilt.android.plugin'
包依赖:
implementation 'com.google.dagger:hilt-android:2.30'
kapt 'com.google.dagger:hilt-android-compiler:2.30'
implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03'
implementation 'androidx.activity:activity-ktx:1.6.1'
- 添加注入
hilt添加的时候是需要在application的类里面添加如下注解:
@HiltAndroidApp
class MyApplication:Application() {
override fun onCreate() {
super.onCreate()
}
}
这个相当于hilt的入口
activity的注入关键字:
@AndroidEntryPoint
class HiltExampleActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_hilt_example)
}
}
给activity中加入注解类:
@Inject
lateinit var myFamily: MyFamily
再到方法里面使用这个类:
Log.i("hiltExample","my family:${myFamily.familyMember()}")
ViewModel的注入:
@HiltViewModel
class HiltExampleViewModel:ViewModel() {
}
- 作用域
我们在dagger里面讲过,dagger里面提供一个Singleton一个作用域,可以自定义作用域,在hilt里面提供了多种作用域:
- @ActivityScoped: activity的生命周期内存在
- @ViewScoped: View的生命周期内存在
- @ViewModelScoped:ViewModel生命周期内存在
- @FragmentScoped:fragment生命周期内存在
- @ServiceScoped:service的生命周期
- hilt中的Module和dagger中的不同
在dagger中Module需要依赖一个自定义的component,但是在dagger里面有几个默认的component:
- ActivityComponent
- ViewModelComponent
- FragmentComponent
- ViewWithFragmentComponent
- ViewComponent
- ServiceComponent
以上分别针对不同的生命周期对应的组件