演示者未插入Dagger 2中的我的活动中

时间:2019-03-08 13:51:09

标签: android kotlin dagger-2

我正在学习Dagger 2以构建一个干净的建筑项目。我一直在寻找关于同一错误的一些SO问题,但仍无法弄清为什么它不起作用。

我已经运行了调试器,以查看我的View Activity是否将发送给演示者,但似乎没有注入演示者,因为它没有提供给演示者。

这是我向“演示者”注入的活动。

ApodDetail.kt

 @Inject lateinit var presenter : ApodDetailPresenter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_apod_detail)
        (application as SimpleMVPApplication).apodComponent.inject(this)
        fetchApodDetails()
        imageview_apoddetail_reloadDetail.bringToFront()
    }

PresenterModule.kt

@Module
class PresenterModule {

    @Provides
    @Singleton
    fun provideApodDetailPresenter(): ApodDetailPresenter {
        return ApodDetailPresenter(ApodDetailsInteractorImpl(), ImageCacheImpl())
    }

}

AppComponent.kt

@Singleton
@Component(modules = [AppModule::class, PresenterModule::class])
interface AppComponent {

    fun inject(target: ApodDetail)
}

AppModule.kt

@Module
class AppModule(private val app: Application) {

    @Provides
    @Singleton
    fun provideContext(): Context = app
}

SimpleMVPApplication.kt

class SimpleMVPApplication: Application() {

    lateinit var apodComponent: AppComponent

    override fun onCreate() {
        super.onCreate()
        apodComponent = initDagger(this)
    }

    private fun initDagger(app: SimpleMVPApplication): AppComponent =
            DaggerAppComponent.builder()
                    .appModule(AppModule(app))
                    .build()
}

这是我要插入ApodDetail.kt

的演示者

ApodDetailPresenter.kt

class ApodDetailPresenter @Inject constructor(apodInteractor: ApodDetailsInteractorImpl, cache: ImageCacheImpl): ApodDetailContract.Presenter {

    var view: ApodDetailContract.View? = null
    var apodInteractor: ApodDetailsInteractorImpl? = null
    var cache: ImageCacheImpl? = null

    init {
        this.view = view
        this.apodInteractor = apodInteractor
        this.cache = cache
    }

就像我上面说的那样,这并不是将演示者注入到我的活动中。

1 个答案:

答案 0 :(得分:0)

在您的Application类中,您缺少在组件构建器中添加presenter模块的调用。您需要:

private fun initDagger(app: SimpleMVPApplication): AppComponent =
            DaggerAppComponent.builder()
                    .appModule(AppModule(app))
                    .presenterModule(PresenterModule())
                    .build()