Referencing the Activity inside its module

2019-06-25 00:29发布

问题:

How do I use the new AndroidInjector.inject and still be able to provide an Activity instance inside an Activity Module? The Dagger docs don`t make it clear how to archive this.

The use case is the following: I have an Activity Module which provides a Presenter to my Activity, but the Presenter needs a reference to the Activity. I used to have something like

@Inject Presenter presenter;

public onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   ((CustomApplication) getApplicationContext())
       .getAppComponent()
       .plus(new ActivityModule(this));
}

Can someone can point me to a sample that uses AndroidInjector.inject(this) instead and allow the reference of the Activity inside the Dagger 2 module?

回答1:

Check Dagger 2 Github issue 615

The instance of your Activity is automatically provided, just pass it as a parameter in your module methods.

Example:

@Provides
@ActivityScope
public providePresenter(ActivityA activity) {
    return new PresenterA(activity);
}

You'll now be able to abstract simple modules. Your presenter can be constructor injected too.

This actually cutout a lot of code from all my modules.