I want to use dagger for my mvp pattern, but lateinit presenter will not initialized when I call its function. Presenter is not private.
here is my dagger ViewModule which provide activity as view for presenter
@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()
}
And my APresenter constructor
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
@Component(modules = [PresenterModule::class, RepoModule::class, ViewModule::class])
@Singleton
interface PresenterComponent {
fun injectMain(view: AView)
}
MainActivity which implements AView interface and inject presenter
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()
}
fun provideAView(): AView = MainActivity()you cannot do this, MainActivity is created by the system and not you - EpicPandaForce