简体   繁体   中英

Dagger + MVP - Problems injecting Presenter in Model

I'm having problems with the dagger dependency cycle, and despite looking for hours, I can not find the solution. I think it's my idea of architecture. What could be wrong? I'm using Dagger 2.11.

Following the codes

Inicio.java

public class Inicio extends BaseFragment implements InicioMvpView {

@Inject
InicioMvpPresenter inicioPresenter;

@Inject
MainMvpPresenter<MainMvpView> mainPresenter;
//...

InicioComponent.java

@Subcomponent(modules = {InicioModule.class})
public interface InicioComponent extends AndroidInjector<Inicio> {

    @Subcomponent.Builder
    abstract class Builder extends AndroidInjector.Builder<Inicio> {
    }
}

InicioModel.java

public class InicioModel implements InicioMvpModel{

    @Inject
    InicioMvpPresenter inicioPresenter;

    @Inject
    public InicioModel() {

    }

    @Override
    public void recuperarAgendamentos() {

        //...

        inicioPresenter.atualizarListaAgendamentos(agendamentos);

    }
}

InicioModule.java

@Module
public class InicioModule {

    @Provides
    InicioMvpView provideInicioView(Inicio inicioFragment){
        return inicioFragment;
    }

    @Provides
    InicioMvpPresenter provideInicioPresenter(
            InicioPresenter presenter) {
        return presenter;
    }

    @Provides
    InicioMvpModel provideInicioModel(InicioModel inicioModel) {
        return inicioModel;
    }
}

InicioPresenter.java

public class InicioPresenter implements InicioMvpPresenter{

    @Inject
    InicioMvpModel inicioModel;

    @Inject
    InicioMvpView inicioMvpView;

    @Inject
    public InicioPresenter() {
    }

    @Override
    public void recuperarAgendamentos(Bundle savedInstanceState) {

    //..

    }
}

Your problem is that you trying to solve a ciclic dependency with Dagger and Dagger doesn't solve this problem.

This can be corrected in your architecture. Just pass a callback to your model instead of passing the Presenter to the Model.

This this:

public class InicioModel implements InicioMvpModel{

@Inject
public InicioModel() {

}

@Override
public void recuperarAgendamentos(Presenter inicioPresenter) {

    //...

      inicioPresenter.atualizarListaAgendamentos(agendamentos);

    }
}

That's it. Just pass the presenter as a parameter in your methods in your model. This makes the communication less coupled.

You can also take a look for RxJava, it removes the need to pass the presenter in the method. Link: https://github.com/ReactiveX/RxJava

There is also a good implementation to follow for MVP by Antonio Leiva: https://github.com/antoniolg/androidmvp

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