演示者中的VIPER注入交互器

时间:2019-07-09 12:59:50

标签: android dagger-2 mvp viper

我有一个采用VIPER架构的应用程序。我将dagger-2与DI配合使用,但无法将交互器注入演示者中。

我得到下一个错误:

lateinit property interactor has not been initialized

我有下一个代码:

MainView(科特林)

interface MainView {

    interface View : BaseView {
        showMessage(message : String)
    }

    interface InteractorOutput{
        ...
    }
}

MainActivity(Kotlin)

class MainActivity : BaseActivity(), MainView.View {

    @Inject lateinit var presenter: MainPresenter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main)
    }

    override fun onCreatePresenter() {
        presenter.setView(this)
        presenter.onCreate()
    }

    override fun initializeDagger() {
        activityComponent.inject(this)
    }

    override fun showMessage(message : String){
        Toast(...)
    }
}

MainPresenter(Kotlin)

class MainPresenter @Inject constructor(): BasePresenter<MainView.View, MainInteractor>(), MainView.InteractorOutput {

    @Inject lateinit var interactor : MainInteractor

    override fun onCreate() {
        interactor.doSomething()
    }
}

MainInteractor(Kotlin)

class MainInteractor: BaseInteractor() {

    fun doSomething() {
        Log.e("Hello ", "World!")
    }
}

ActivityComponent(Java)

@PerActivity
@Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class})
public interface ActivityComponent {
    void inject(MainActivity mainActivity);
}

ActivityModule(Java)

@Module
public class ActivityModule {

    private final BaseActivity mActivity;

    public ActivityModule(BaseActivity activity) {
       mActivity = activity;
    }

    @Provides
    @PerActivity
    BaseActivity activity() {
        return mActivity;
    }

    @Provides
    @PerActivity
    MainPresenter provideMainPresenter() {
        return new MainPresenter();
    }
}

ApplicationComponent(Java)

@Singleton
@Component(modules = {ApplicationModule.class})
public interface ApplicationComponent {

    void inject(BaseActivity baseActivity);

}

ApplicationModule(Java)

@Module
public class ApplicationModule {

    private final BaseApplication mApplication;

    public ApplicationModule(BaseApplication application) {
        mApplication = application;
    }

    @Provides
    @Singleton
    Context provideApplicationContext() {
        return mApplication;
    }
}

1 个答案:

答案 0 :(得分:1)

当前,您已将您的交互器设置为要插入的字段。但是,没有注入该字段的机制,实际上没有必要这样做,因为应该使用构造函数注入。

从演示者中删除以下内容:

@Inject lateinit var interactor: MainInteractor

,而是将其注入构造函数中:

class MainPresenter @Inject constructor(private val interactor: MainInteractor)

目前Dagger也无法提供MainInteractor,因此您需要使用以下命令注释其构造函数:

class MainInteractor: BaseInteractor @Inject constructor () {

我不清楚MainPresenterMainActivityPresenter之间的区别是什么,您可能还有其他问题。这些更改应该使您更接近。