0

I've read that constructor injections don't require a module. So I have this questions.

  1. If I have this constructor injection:

    private Model realmModel;
    
    @Inject
    public MainActivityPresenter(Model realmModel) {
        this.realmModel = realmModel;
    }
    

and this component:

@Singleton
@Component(modules = {AppModule.class})
public interface AppComponent {


    Model realmModel();
    void inject(MainActivity activity);


}

if in my MainActivity I do it:

((MyApp)getApplication()).createAppComponent().inject(this);

how could I pass the realmModel parameter to the presenter constructor injection?

EDIT: this is the model:

 Presenter presenter;

 @Inject
 public RealmModel(Presenter presenter) {
    this.presenter = presenter;

}

Thanks

nani
  • 382
  • 5
  • 15
  • You have a cyclic dependency here and you should try to get rid of it. Your model depends on the presenter and the presenter depends on the model. Hence you will not be able to constructor inject either, since neither can be created without the other being created first. Does your model really need to keep a reference to the presenter? – David Medenjak May 22 '17 at 19:55
  • @DavidMedenjak not sure, I could make a callback to handle the results to the presenter, but without it this works? – nani May 23 '17 at 10:42

2 Answers2

1

Three ways to solve this problem

1) Give a module which does the provide of the Relam Model

 @Provides
 @Singleton
 public Model providesRealmModel() {
     return new Model();
 }

2) Make your RelamModel class also constructor injected

class Model {
   @Inject
   public Model() {}
} 

The Trick in construction injection is all its dependencies should also be constuctor injeceted then it would work fine. (From experience your model would need application context. look at the 3 option for ways to implement external Dependencies

3) Provide Model as external dependency.

 @Module
 public class ModelModule {
    private Model relamModel;
    public ModelModule(Model relamModel) {
       this.relamModel = relamModel
    }
 }

@Component(module={ModelModule.class}) 
public interface ApplicationComponent {
}

Take a look at the series of videos from twisted eqautions these were my first video tutorial on dagger2. I found it really helpful. Hope it helps you too https://www.youtube.com/watch?v=Qwk7ESmaCq0

Jileshl
  • 146
  • 6
0

You have two choices:

  1. use a module with a provide method
  2. annotate the constructor of Model with @Inject, doing that when you pass realmModel in the presenter contructor, the model constructor will be called.

I prefer to use modules, but that's just my opinion.

Matias Elorriaga
  • 8,880
  • 5
  • 40
  • 58