简体   繁体   中英

Dagger2 inject lateinit var presenter in activity not working

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()
}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM