Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between addsTo and includes in Java's Dagger?

Tags:

android

dagger

I am not sure what the difference is? When should I use which?

http://square.github.io/dagger/javadoc/index.html

like image 652
Kamilski81 Avatar asked Dec 26 '22 00:12

Kamilski81


1 Answers

includes indicates which modules current module is composed of. For example, it's useful for aggregating all your modules statically:

@Module(
  includes = { AndroidModule.class, NetworkModule.class, StorageModule.class }
)
public class RootModule() {
}

// other file
objectGraph = ObjectGraph.create(new RootModule());

Instead of dynamically:

objectGraph = ObjectGraph.create(
     new AndroidModule(), 
     new NetworkModule(), 
     new StorageModule());

Thus, fully utilizing compile time graph validation.

addsTo relates specifically to parent-child modules' relations. It indicates that module is an extension of some module and is used as .plus() parameter. E.g. having two modules:

@Module(
  //...
)
public class ParentModule() {
  //...
}

@Module(
  addsTo = { ParentModule.class },
  //...
)
public class ChildModule () {
  //...
}

this config means that after parentGraph = ObjectGraph.create(new ParentModule()); you can execute childGraph = parentGraph.plus(new ChildModule()); somewhere in your code to create extended, usually, short-lived child graph.

like image 200
colriot Avatar answered Feb 02 '23 04:02

colriot