Android Dagger 2 and MVP injecting inside an injected object

I want to use dagger 2 with an MVP pattern. Therefore, I have this scenario, each Viewhas its own Componentexample. MyFragmenthas such a component:

@PerFragment @Component(dependencies = ActivityComponent.class, modules = MyFragmentModule.class)
public interface MyFragmentComponent {
  void inject(MyFragment fragment);
}

And in MyFragmentModuleI introduced a presenter and a model to be used inMyFragment

@Module public class MyFragmentModule {

  @Provides @PerFragment public MyPresenter providePresenter() {
    return new MyPresenter();
  }

  @Provides @PerFragment public Model provideModel() {
    return new Model();
  }
}

Now I insert the component in MyFragment:

public class MyFragment extends Fragment{
       @Inject MyPresenter presenter;

@Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    component = DaggerMyFragmentComponent.builder()...build();
    component.inject(this);
  }
}

Also MyPresenterlooks like this:

   public class MyPresenter {

      @Inject Model model;
}

Question

I do not know how to type Modelin my presenter. I do not want to introduce a component in my presenter, like what I did in MyFragment.

Is there a way for this approach?

+4
source share
1 answer

, , . , Presenter, , , , .

@Module
public class MyFragmentModule {
    private MyFragment myFragment;

    public MyFragmentModule(MyFragment myFragment) {
        this.myFragment = myFragment;
    }

    @Provides
    public MyFragment myFragment() {
        return myFragment;
    }

    @Provides @PerFragment public MyPresenter providePresenter(MyFragment myFragment) {
        return new MyPresenter(myFragment);
    }

    @Provides @PerFragment public Model provideModel(MyFragment myFragment) {
        return new Model(myFragment);
    }        
}

public class MyPresenter {
    @Inject Model model;

    public MyPresenter(MyFragment myFragment) {
        myFragment.getComponent().inject(this);
    }
}

- .

public class MyPresenter {
    private Model model;

    public MyPresenter(Model model) {
        this.model = model;
    }
}

    @Provides @PerFragment public MyPresenter providePresenter(Model model) {
        return new MyPresenter(model);
    }

EDIT: @Inject .

@PerFragment
public class MyPresenter {
    private Model model;

    @Inject
    public MyPresenter(Model model) {
        this.model = model;
    }
 }

@PerFragment
public class MyPresenter {
    @Inject
    Model model;

    @Inject
    public MyPresenter() {
    }
 }
+4

Source: https://habr.com/ru/post/1619704/


All Articles