Reputation: 33
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()
}
Upvotes: 0
Views: 446
Reputation: 2290
You need to specify the exact type in inject(...)
methods of the Component
interface. Otherwise, the members won't be injected. (See this comment for more explanation)
So change your component class to this:
@Component(modules = [PresenterModule::class, RepoModule::class, ViewModule::class])
@Singleton
interface PresenterComponent {
fun injectMain(view: MainActivity) //<-- The AView is changed to MainActivity
}
Upvotes: 1