Home » Android » Exposing/providing/injecting Activity to graph using dagger-android

Exposing/providing/injecting Activity to graph using dagger-android

Posted by: admin November 1, 2017 Leave a comment

Questions:

When previously using Dagger 2.10, I had a pretty typical setup with an ActivitySubcomponent that had an ActivityModule which provided/exposed the Activity instance to the graph to be injected into other classes that required it.

With an ActivityModule like this:

@Module
public class ActivityModule {
    private final Activity activity;

    public ActivityModule(Activity activity) {
        this.activity = activity;
    }

    /**
     * Expose the activity to the graph.
     */
    @Provides @ActivityScope
    Activity activity() {
        return activity;
    }
}

Which would get the Activity instance by creating a new ActivityModule like this just before injecting:

    @Inject PermissionsHelper permissionsHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        DaggerApplicationComponent.builder()
            .applicationModule(new ApplicationModule(getApplicationContext()))
            .plus(new ActivityModule(this))
            .inject(this);
    }

I could provide the Activity to something like this:

@ActivityScope
public class PermissionsHelper {

    private final Activity activity;

    @Inject
    PermissionsHelper(Activity activity) {
        this.activity = activity;
    }
}

However, after migrating to the new dagger-android setup (using this as a guide), I no longer have easy access to the Activity instance without creating a separate module for each injected activity and then binding it’s instance to an Activity object like so:

@Module
abstract class ActivityBindingModule {

    @ActivityScope
    @ContributesAndroidInjector(modules = arrayOf(SomeActivityModule::class))
    abstract fun someActivity(): SomeActivity
}

@Module
abstract class SomeActivityModule {

    /**
     * Expose the activity to the graph.
     */
    @Binds
    abstract fun bindActivity(someActivity: SomeActivity): Activity
}

While using the new dagger-android stuff, is there any way of avoiding that last step of creating a module, and binding it, for each Activity where I want its seed instance exposed to graph?

Answers: