Per scope dependency / overrideing dependencies per scope in Dagger2

53 Views Asked by At

I think the easiest way to explain is with a code example that includes RxJava

class SomeClass {
    CompositeSubscriptions subscriptions;
    public SomeClass(CompositeSubscription subscriptions) {
         this.subscriptions = subscriptions;
         subscriptions.add(...);
         subscriptions.add(...);
         subscriptions.add(...);
         subscriptions.add(...);
         subscriptions.add(...);
    }

    public void destory() {
        subscriptions.unsubscribe();
    }
}

So what I want to be able to do is to have classes just be able to ask for a CompositeSubscription and they get the one for there scope. That way they can freely unsubscribe the whole CompositeSubscription. This would be needed so that my Singletons don't interfere with my Activities which don't interfere with my Fragments.

1

There are 1 best solutions below

0
On BEST ANSWER

You cannot have the same class provided in multiple scopes. You get an error {Class} is bound multiple times.

So the following setup is not valid

@Module
public class ActivityRxJavaModule {

    @Provides
    @PerActivity
    CompositeSubscription providesCompositeSubscription() {
        return new CompositeSubscription();
    }
}

@Module
public class FragmentRxJavaModule {

    @Provides
    @PerFragment
    CompositeSubscription providesCompositeSubscription() {
        return new CompositeSubscription();
    }
}

So there are two solutions that I know of.

  1. Subclass per scope a. Singleton{Class}, PerWhatever{Class}
  2. Using the name annotation a. @Named("singleton"), @Named("perwhatever")

I seem to prefer the Subclass per scope because I feel like it is a bit safer when refactoring, but both should work.