Injecting Generics in Dagger

℡╲_俬逩灬. 提交于 2019-12-01 17:00:32

问题


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

public abstract class Presenter<T extends BaseView> {

    @Inject T mView;

    public void showLoadingIndicator() {
        mView.showLoading();
    }

}

(example module)

public class MyModule {
    private MyView mView; //extends BaseView

    public MyModule(MyView view) {
        mView = view;
    }

    @Provides
    public BaseView provideView() {
        return mView;
    }

}

And then create an object graph with the module above and inject the view into the presenter?

My attempts have not worked (usually get "unknown class 'T'" sort of errors). I'm not sure if my configuration is wrong or if this is unsupported functionality.


回答1:


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



来源:https://stackoverflow.com/questions/28224927/injecting-generics-in-dagger

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!