Presenter injection with Dagger 2

后端 未结 2 543
情深已故
情深已故 2021-02-08 05:04

I just started using Dagger 2 and I found online thousands guides each one with a different implementation and I\'m a bit confused now. So basically this is what I wrote at the

相关标签:
2条回答
  • 2021-02-08 05:26

    You are mixing thing up. To provide your presenter, you should switch to something like the following:

    Use constructor injection if possible. It will make things much easier

    public class HomePresenterImpl {
    
        @Inject
        public HomePresenterImpl(NetworkService networkService) {
            // ...
        }
    
    }
    

    To provide the interface use this constructor injection and depend on the implementation:

    Presenter<FwView> provideHomePresenter(HomePresenterImpl homePresenter) {
        return homePresenter;
    }
    

    This way you don't have to call any constructors yourself. And to actually inject the presenter...

    public class MyFragment extends Fragment {
    
        @Inject
        Presenter<FwView> mHomePresenter;
    
        public void onCreate(Bundle xxx) {
            // simplified. Add your modules / Singleton component
            PresenterComponent component = DaggerPresenterComponent.create().inject(this);
        }
    }
    

    This way you will inject the things. Please read this carefully and try to understand it. This will fix your major problems, you still can not provide 2 presenters of the same type from the same module (in the same scope)

    // DON'T
    @Provides
    Presenter<FwView> provideHomePresenter(NetworkService networkService) { /**/ }
    
    @Provides
    Presenter<FwView> provideSearchPresenter(NetworkService networkService) { /**/ }
    

    This will not work. You can not provide 2 objects of the same kind. They are indistinguishable. Have a look at @Qualifiers like @Named if you are sure this is the way you want to go.

    0 讨论(0)
  • 2021-02-08 05:43

    You do not have to provide Presenter if @Inject annotation is used in the constructor. @Inject annotation used in the constructor of the class makes that class a part of dependencies graph. So, it also can be injected when needed.

    On the other hand, if you add @Inject annotation to fields, but not to constructors, you have to provide that class.

    0 讨论(0)
提交回复
热议问题