rpattabi
rpattabi

Reputation: 10207

How to add an object created elsewhere as dagger dependency?

I wonder how to add an object created elsewhere as dependency to be provided by dagger module.

For example, I am using data binding. MainActivity::onCreate() gets ActivityMainBinding object after layout is inflated like this:

ActivityMainBinding binding = 
            DataBindingUtil.setContentView(this, R.layout.activity_main);

Now, how can I make this binding object available elsewhere through dagger module?

Upvotes: 0

Views: 366

Answers (1)

Kevin Krumwiede
Kevin Krumwiede

Reputation: 10288

You can pass it to the module's constructor and return it (or something derived from it) from a @Provides method. For example:

@AppScope
@Module
public class AppModule {
    private final Context mContext;

    public AppModule(@NonNull final Context context) {
        mContext = context.getApplicationContext();
    }

    @Provides
    @AppScope
    Context provideApplicationContext() {
        return mContext;
    }

    // more @Provides methods...
}

If you have activity-scoped dependencies, the activity can create a submodule using this same approach. Fragments can then get the activity's Dagger component and inject themselves.

Upvotes: 1

Related Questions