arash moeen
arash moeen

Reputation: 4713

Dagger 2 multiple component with the same dependency

I'm new to dependency injection and I'm not even sure if this is the right approach.

What I'm trying to do is to have 2 different component sharing the same dependency. For example I have my lottery component + its module as:

@PerActivity
@Component(dependencies = NetworkComponent.class,
        modules = {
                LotteryModule.class
        })
public interface LotteryComponent {
    void inject(DashboardFragment fragment);

    LotteryApiInterface lotteryApiInterface();
}

@Module
public class LotteryModule {

    @Provides
    @PerActivity
    public LotteryApiInterface providesLotteryApiInterface(Retrofit retrofit) {
        return retrofit.create(LotteryApiInterface.class);
    }
}

and here is the spending component + its module:

@PerActivity
@Component( dependencies = NetworkComponent.class, modules = SpendingModule.class )
public interface SpendingComponent {
    void inject(DashboardFragment fragment);

    SpendingApiInterface spendingApiInterface();
}


@Module
public class SpendingModule {

    @Provides
    @PerActivity
    public SpendingApiInterface providesSpendingApiInterface(Retrofit retrofit) {
        return retrofit.create(SpendingApiInterface.class);
    }
}

Is that possible for those 2 Components to share a same Dependency? How's the best approach to implement this?

Thank you

Upvotes: 2

Views: 2076

Answers (1)

shekar
shekar

Reputation: 1271

Yes, it is possible for 2 Components to share the same Dependency but make sure dependency are not redundant.

In your case, I don't see any advantage of creating two component instead you can create one component and one Module which will return LotteryApiInterface or SpendingApiInterface services.

If LotteryApiInterface or SpendingApiInterface services are not used anywhere else other then DashboardFragment then you can make your component as Subcomponent of NetworkComponent, by doing so you need not expose your dependency in Component.

Ex

@PerActivity
@Subcomponent( modules = LotterySpendingModule.class )
public interface LotterySpendingComponent {
    void inject(DashboardFragment fragment);
}

and in NetworkComponent

public interface NetworkComponent {
    LotterySpendingComponent plus(LotterySpendingModule module);
}

Upvotes: 1

Related Questions