1
votes

I'm trying to create an Android library alongside another project whilst learning DI with Dagger 2. It's proving to be more difficult than expected.

My Question

I'm trying to use a singleton class called MySingleton that I want to access from both my Android library as well as the main application.

Current Setup

Basically I have a singleton class called MySingleton in my Android library project. In the project I have a class called SingletonModule which is a Dagger2 module that provides my singleton like so.

@Provides @Singleton
MySingleton providesMySingleton() {
    return new MySingleton();
}

Ok, now in my actual application in I have the following component.

@Singleton
@Component(modules = {SingletonModule.class})
public interface ApplicationComponent {
    void inject( MyApplication application );
}

So this is used to inject MySingleton into the MyApplication class. It does it like so.

this.applicationComponent = DaggerApplicationComponent.builder()
            .singletonModule( new SingletonModule() ) // does it for you as empty constructor
            .build();
    applicationComponent.inject(this);

This is great and the instance of MySingleton that I'm injecting by field is working fine.

What I have Tried

In my Android library project I created a new component called SingletonComponent which did the same as ApplicationComponent, just provided the MySingleton object. Then in the MyService class which extends Service I injected, by field, the MySingleton object. This did not have the effect I was after. It did object a MySingleton object but it was not the same instance as created when injecting into my actual application. I believe this is because it is a new component that I'm creating...

What am I doing wrong here?

I have looked on many different sites and followed many tutorials but something just isn't clicking with this dependency injection.

1

1 Answers

1
votes

I believe this is because it is a new component that I'm creating...

You are absolutely correct. Singletons are unique per dependency graph. When creating second component you are essentially creating second dependency graph which have different object for that singleton.

There are two solutions:

  1. Create just one graph in your app that includes the lib modules
  2. Create one graph in you lib, and then add your app module(s) to it (like in: https://github.com/google/dagger/tree/master/examples/android-activity-graphs (they are adding "per activity" module there but you will get the idea))