这个一个简单的例子;介绍如何在Kotlin-MVP中使用dagger2(v2.11+),基本使用就不介绍了,还是跟之前版本还是一样,只是设计到activity/Fragment的时候有点不一样
//dagger2
compile 'com.google.dagger:dagger-android:2.11'
compile 'com.google.dagger:dagger-android-support:2.11'
kapt 'com.google.dagger:dagger-android-processor:2.11'
kapt 'com.google.dagger:dagger-compiler:2.11'
在build.gradle最外层结果添加:
kapt {
generateStubs = true
}
data class UserInfo(var name: String, var age: Int)
class MainModel {
interface CallBack {
fun data(info: UserInfo)
}
fun getInfo(callBack: CallBack) {
callBack.data(UserInfo("Kotlin", 3))
}
}
class MainPresenter @Inject constructor(var model: MainModel?, var view: MainView?) {
fun getInfo() {
model?.getInfo(object : MainModel.CallBack {
override fun data(info: UserInfo) {
view?.showInfo(info)
}
})
}
fun destroy() {
model = null
view = null
}
}
@Module
class MainPresenterModule {
@Provides
fun modelProvider(): MainModel {
return MainModel()
}
@Provides
fun viewProvider(activity: MainActivity): MainView {
return activity
}
}
@Subcomponent(modules = arrayOf(MainPresenterModule::class))
interface MainSubComponent : AndroidInjector<MainActivity> {
@Subcomponent.Builder
abstract class Builder : AndroidInjector.Builder<MainActivity>()
}
@Module
abstract class MainActivityModule {
@Binds
@IntoMap
@ActivityKey(MainActivity::class)
internal abstract fun bind(builder: MainSubComponent.Builder): AndroidInjector.Factory<out Activity>
}
@Module(subcomponents = arrayOf(MainSubComponent::class))
class AppModule {
@Provides
fun contextProvider(application: MyApplication): Context {
return application.applicationContext
}
}
@Component(modules = arrayOf(
/* Use AndroidInjectionModule.class if you're not using support library */
AndroidSupportInjectionModule::class,
AppModule::class,
MainActivityModule::class
))
interface AppComponent {
fun inject(application: MyApplication)
}
class MyApplication : Application(), HasActivityInjector {
@Inject
lateinit var dispatchingActivityInjector: DispatchingAndroidInjector
override fun activityInjector(): AndroidInjector {
return dispatchingActivityInjector
}
}
到这里点击AS的build,完成没有报错之后再application的onCreate方法下:
override fun onCreate() {
super.onCreate()
DaggerAppComponent.create()
.inject(this)
}
MainActivity
创建MainPresenter
的变量 @Inject
lateinit var presenter: MainPresenter
onCreate
里super语句之前加上(这句代码一样要加在super之前) AndroidInjection.inject(this)
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
presenter.getInfo()
}
build一下就全部搞定完成了;
本文demo源码 ;
若你感兴趣欢迎start,也可以看看我用kotlin与dagger2写的项目: https://github.com/a1018875550/ZhihuDaily