如何用Koin注入来自主持人的交互者

时间:2019-06-14 12:27:44

标签: android kotlin koin

我是Koin的新朋友。我已经准备好所有东西,并且正在工作。但是,当我尝试同时注入交互器和演示者时,遇到了一些问题。那不确定是否有可能。

这是我的模块

val applicationModule = module(override = true) {
    factory{VoucherImpl(get())}
    factory<VoucherContract.Presenter> { (view: VoucherContract.View) -> VoucherPresenter(view, get()) }


}

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

 private val presenter: VoucherContract.Presenter by inject { parametersOf(this)}

这是我的演示者

class VoucherPresenter (private var view: VoucherContract.View?, private var mCodeRechargeInteract : VoucherImpl) : VoucherContract.Presenter, VoucherContract.Callback, KoinComponent {

    override fun create() {
        view?.initView()
        view?.showProgress()
        mCodeRechargeInteract.run()
    }
.
.
.

Interactor类

class VoucherImpl(private var mCallback: VoucherContract.Callback?) : AbstractInteractor() {
.
.
.

合同

interface VoucherContract {


    interface Presenter {
        fun create()
        fun destroy()
        fun checkIfShoppingCartHaveItems()
        fun addVoucherToShoppingCart(voucherProduct: Product)
        fun onItemClick(product: Product)
    }

    interface Callback {
        fun onResponseVouchers(vouchers: List<Product>?)
        fun onError()
    }

}

有了这个代码,我得到了

No definition found for 'xxx.voucher.VoucherContract$Callback' has been found. Check your module definitions.

然后,我尝试将其放入模块中,但由于以下原因而无法执行操作:类型不匹配。必需VoucherContract.Callback找到VoucherImpl

factory<VoucherContract.Callback> { (callBack: VoucherContract.Callback) -> VoucherImpl(callBack) }

1 个答案:

答案 0 :(得分:1)

您有一个循环依赖,这就是为什么它不起作用的原因。

VoucherImpl(VoucherContract.Callback)VoucherPresenter(View, VoucherImpl):VoucherContract.Callback

有多种方法可以摆脱这种困境。 我建议进行以下更改: VoucherImpl不应具有构造函数参数VoucherContract.Callback。此回调应为类似以下方法的参数:

class VoucherImpl : AbstractInteractor(){
  fun listen(VoucherContract.Callback){...}
}

通过这种方式,依赖关系成为一种方式,您可以注入它们。

相关问题