Inheritance and dependency injection with Roboguice and RxJava

181 views Asked by At

I have one base class and 2 derived classes. I will attempt to explain with a very simplified version:

public class AllIntegers{
    List<Integer> myList;
    BehaviorSubjec<Integer> behaviorSubject;
    @Inject
    public AllIntegers(List<Integers> allIntegers) {
       behaviorSubject = BehaviorSubject.create();
       //some logic
    }
    public BehaviorSubject<Integer> getAllIntegersBSAsObservable() {
      return this.behaviorSubject.asObservable();
    }
}


public class OddIntegers extends AllIntegers {
    List<Integer> myList;

    @Inject
    public OddIntegers(... some dependencies...) {
       /* ... some logic ... */
       //Getting observable from parent
       getAllIntegersBSAsObservable.subscribe(new Subscriber(...));
    }
}

public class EventIntegers extends AllIntegers {
    List<Integer> myList;

    @Inject
    public EventIntegers(... some dependencies...) {
       /* ... some logic ... */
       //Getting observable from parent
       getAllIntegersBSAsObservable.subscribe(new Subscriber(...));
    }
}

My Roboguice module file looks like this:

bind(IAllIntegers.class).to(AllIntegers.class).in(Scopes.SINGLETON);
bind(IOddIntegers.class).to(OddIntegers.class).in(Scopes.SINGLETON);
bind(IEventIntegers.class).to(EventIntegers.class).in(Scopes.SINGLETON);

Again, I OVER simplified here to make it easier to write and understand.

The problem is that Roboguice creates an instance of AllIntegers.class as it should. I have to however add an empty constructor to the AllIntegers.class for the compiler to not complain, this of course causes OddIntegers and EventIntegers to EACH get their OWN instance of AllIntegers, so both children get different instances of the observable while the singleton base class also gets its own (this is the one I actually want), so when I fire onNext on the behavior subject, the children do not react because the behavior subject is different.

Should I be using composition instead of inheritance?

1

There are 1 answers

1
Jorn Vernee On

I don't think Roboguice is the problem, this is standard behaviour. You're calling getAllIntegersBSAsObservable, an instance method, wich returns this.behaviorSubject.asObservable(); an instance field. Even though all instances are singletons, they are still separate instances, so they each have their own instance of behaviorSubject.


A possible fix is to make behaviorSubject a static field.