Presenter injection with Dagger 2

后端 未结 2 544
情深已故
情深已故 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 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 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 provideHomePresenter(NetworkService networkService) { /**/ }
    
    @Provides
    Presenter 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.

提交回复
热议问题