我想在我的MVP模式中使用匕首, 但当我调用函数时,lateinit Presenter不会初始化。 主持人不是私人的。
这是我的匕首ViewModule,它为演示者提供活动作为视图
@Module
class ViewModule {
@Provides
fun provideAView(): AView = MainActivity()
}
PresenterModule
@Module
class PresenterModule {
@Provides
fun provideAPresenter(repo: ARepo, view: AView): APresenter = APresenter(repo, view)
}
RepoModule
@Module
class RepoModule {
@Provides
fun provideARepo(): ARepo = ARepo()
}
还有我的APresenter构造函数
class APresenter @Inject constructor(var repo: ARepo, var view: AView) {
fun showHelloWorld() {
val i = repo.repo()
Log.d("main", "aPresenter repo : $i")
view.helloWorld()
}
}
组件
@Component(modules = [PresenterModule::class, RepoModule::class, ViewModule::class])
@Singleton
interface PresenterComponent {
fun injectMain(view: AView)
}
MainActivity,它实现AView界面并注入演示者
class MainActivity : AppCompatActivity(), AView, BView {
@Inject
lateinit var aPresenter: APresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val component = DaggerPresenterComponent.create()
component.injectMain(this)
// but this presenter will not init at this time and cause
// lateinit property not init exception.
aPresenter.showHelloWorld()
}
答案 0 :(得分:1)
您需要在inject(...)
接口的Component
方法中指定确切的类型。否则,将不会注入成员。 (有关更多说明,请参见此comment)
因此将您的组件类更改为:
@Component(modules = [PresenterModule::class, RepoModule::class, ViewModule::class])
@Singleton
interface PresenterComponent {
fun injectMain(view: MainActivity) //<-- The AView is changed to MainActivity
}