Generic Injection in a Dagger

Is it possible to do something like the following in a dagger:

public abstract class Presenter<T extends BaseView> { @Inject T mView; public void showLoadingIndicator() { mView.showLoading(); } } 

(module example)

 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 using the module above and enter the view in the presenter?

My attempts did not work (as a rule, they get an “unknown class" T "). I'm not sure if my configuration is incorrect or if this is unsupported functionality.

+6
source share
1 answer

There is a simple / obvious workaround to achieve the same, depending on how the rest of your code looks.

Without using field injection to initialize the mView field of the base presenter, you can simply pass it to the constructor and provide it with a module, for example:

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

provided that it is used as follows:

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

and the module creates the presenter and gives him the view:

 @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 for objects not created by the dagger, such as activity level or fragment, of course, where we cannot escape @Inject ).

here is the code

+2
source

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


All Articles