Search code examples
androidkotlinkoin

How can inject interactor from presenter with Koin


I'm new at Koin. I have set all the stuff and is working. But I'm getting some problems when I'm trying to inject interactor and presenter at the same time. That not sure it is possible.

This is my Module

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


}

This is my Activity where inject the presenter

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

This is my Presenter

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

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

contract

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

}

With this code I get

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

Then, I try to put it in the module and I can't do it because I get: a Type mismatch. Required VoucherContract.Callback Found VoucherImpl

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

Solution

  • You have a circular dependency that's why this doesn't work.

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

    There are multiple ways out of this predicament. I would recommend the following changes: The VoucherImpl should not have the constructor parameter VoucherContract.Callback. This callback should be the parameter of a method something like this:

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

    This way the dependency becomes one way and you can inject them.