Injecting Generics in Dagger

前端 未结 1 1444
北荒
北荒 2021-01-18 11:44

Is it possible in Dagger to do something like the following:

public abstract class Presenter {

    @Inject T mView;

    public vo         


        
相关标签:
1条回答
  • 2021-01-18 11:58

    There's a simple/obvious workaround to achieve the same thing, depending on what the rest of your code looks like.

    By not using field injection to initialize the mView field of the base presenter, you could just pass it into the constructor, and let the Module provide it, like:

    public abstract class Presenter<T extends BaseView> {
        private final T mView;
    
        public Presenter(T view) {
            mView = view;
        }
    
        public void showLoadingIndicator() {
            mView.showLoading();
        }
    }
    

    assuming it's used like this:

    public class MainPresenter extends Presenter<MainActivity> {
        public MainPresenter(MainActivity view) {
            super(view);
        }
    }
    

    and the module creates the presenter and passes the view to it:

    @Module(injects = MainActivity.class)
    public class MainModule {
        private final MainActivity mMainActivity;
    
        public MainModule(MainActivity mainActivity) {
            mMainActivity = mainActivity;
        }
    
        @Provides
        MainPresenter mainPresenter() {
            return new MainPresenter(mMainActivity);
        }
    }
    

    I prefer this anyway, because I prefer constructor injection over field injection (except on the objects not created by Dagger such as the activity or fragment level of course, where we can't avoid @Inject).

    code here

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