SlideShare une entreprise Scribd logo
1  sur  44
Sword Fighting with Dagger
Mike Nakhimovich
Android Engineer NY Times
What is Dagger?
Dagger offers an alternative way to instantiate
and manage your objects through
Dependency Injection
Dagger 2 open sourced by Google
Dagger 1 – Square
Guice – Google (Dagger v.0)
Compile Time Annotation Processing (Fast)
Superpowers
Lazy
Singleton
Provider
Why Dagger?
In the Olden Days...
Old Way
public class RedditView {
private RedditPresenter presenter;
public RedditView(...) {
Gson gson = new GsonBuilder().create();
RedditApi redditApi = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.build().create(RedditApi.class);
RedditDAO redditDAO = new RedditDAO(redditApi);
presenter=new RedditPresenter(redditDAO);
}
Externalize Object Creation
@Provides
Gson provideGson() {
}
Create a Provider
return new GsonBuilder().create();
}
Modules
A Module is a part of your application that provides
implementations.
@Module public class DataModule {
}
@Provides Gson provideGson() {
return gsonBuilder.create();}
Dependencies
@Provides methods can have their own dependencies
@Provides
RedditApi provideRedditApi(Gson gson) {
return new Retrofit.Builder()
.addConverterFactory(
GsonConverterFactory.create(gson))
.build().create(RedditApi.class);
}
Provides not necessary
You can also annotate constructors directly to register
public class RedditDAO {
@Inject
public RedditDAO(RedditApi api) {
super();
}
}
Provided by Module
Consuming Dependencies
Components
A component is a part of your application that consumes
functionality. Built from Module(s)
@Component( modules = {DataModule.class})
public interface AppComponent {
void inject(RedditView a);
}
Register with Component
Activities/Services/Views register with an instance of a
component
public RedditView(Context context) {
getComponent().inject(this);
}
Injection Fun
Now you can inject any dependencies
managed by the component.
As a field As a Constructor Param
Instantiating Dependencies Old Way
RedditPresenter presenter;
public RedditView(Context context) {
super(context);
Gson gson = new GsonBuilder().create();
RedditApi redditApi = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
.create(RedditApi.class);
RedditDAO redditDAO = new RedditDAO(redditApi);
presenter=new RedditPresenter(redditDAO);
}
Once RedditView registers itself with a component,
Dagger will satisfy all managed dependencies with
@Inject annotations
@Inject RedditPresenter presenter;
public RedditView(...) {
getComponent().inject(this);
}
Instantiating Dependencies Dagger Way
How does Dagger do it?
A static DaggerAppComponent.builder() call creates a Builder instance;
Builder creates an DaggerAppComponent instance;
DaggerAppComponent creates a RedditView_MembersInjector instance;
RedditView_MembersInjectorr uses RedditPresenter_Factory to
instantiate RedditPresenter and injects it into RedditView.
Just as fast as hand written code but with fewer errors
Generated Code
@Generated("dagger.internal.codegen.ComponentProcessor")
public final class RedditPresenter_Factory implements Factory<RedditPresenter> {
private final MembersInjector<RedditPresenter> membersInjector;
public RedditPresenter_Factory(MembersInjector<RedditPresenter> membersInjector) {
assert membersInjector != null;
this.membersInjector = membersInjector;
}
@Override
public RedditPresenter get() {
RedditPresenter instance = new RedditPresenter();
membersInjector.injectMembers(instance);
return instance;
}
public static Factory<RedditPresenter> create(MembersInjector<RedditPresenter> membersInjector) {
return new RedditPresenter_Factory(membersInjector);
}
}
Dependency Chain
The Presenter has its own dependency
public class RedditPresenter {
@Inject RedditDAO dao;
}
Dependency Chain
Which has its own dependency
public class RedditDAO {
private final RedditApi api;
@Inject
public RedditDAO(RedditApi api) {
this.api = api;
}
Dagger Eliminates “Passing Through”
Constructor Arguments
Old Way
RedditPresenter presenter;
public RedditView(...) {
super(context);
Gson gson = new GsonBuilder().create();
RedditApi redditApi = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
.create(RedditApi.class);
RedditDAO redditDAO = new RedditDAO(redditApi);
presenter=new RedditPresenter(redditDAO);
}
Dagger Eliminates “Passing Through”
Constructor Arguments
Dagger Way:
Inject ONLY the dependencies each
object needs
Type of Injections
Dagger has a few types of injection:
Direct
Lazy
Provider
Direct
When instance is created also create the
dependency.
public class RedditPresenter {
@Inject RedditDAO dao;
}
Lazy
Do not instantiate until .get() is called.
public class RedditPresenter {
@Inject Lazy<RedditDAO> dao;
}
Useful to keep startup time down
Provider
Provider<T> allows you to inject multiple
instances of same object by calling .get()
public class RedditPresenter {
@Inject Provider<RedditDAO>
dao;
}
Singletons Old Way
public class MainActivity extends Activity {
SharedPreferences pref;
Gson gson;
ServerAPI api;
onCreate(...) {
MyApp app = (MyApp)getContext().getApplicationContext();
pref = app.getSharedPreferences();
gson = app.getGson();
api = app.getApi();
Why is MYApp managing all singletons?
:-(
Singletons Dagger Way
Define objects to be Singletons
@Singleton @Provides
Gson provideGson() {
return gsonBuilder.create();
}
Singletons Dagger Way
Define objects to be Singletons
@Singleton
public class RedditDAO{
@Inject
public RedditDAO() {
}
Singleton Management
@Singleton = Single instance per Component
@Singleton
@Component( modules = {DataModule.class})
public interface AppComponent {
void inject(RedditView a);
}
Scopes
Singleton is a scope annotation
@Scope
@Documented
@Retention(RUNTIME)
public @interface Singleton {}
We can create custom scope annotations
Subcomponent
Creating a Subcomponent with a scope
@Subcomponent(modules = {
ActivityModule.class})
@ActivityScope
public interface ActivityComponent
Subcomponent
plussing your component into another
component will inherit all objects
Injecting Activities
Components scoped (recreated) with each activity allows us to do silly things
like injecting an activity into scoped objects:
@ScopeActivity
public class Toaster {
@Inject Activity activity;
private static void showToast() {
Toast.makeText(activity, message).show();
}}
Inject a Scoped Object
@Inject
SnackbarUtil snackbarUtil;
there’s no need to pass activity into presenter and then
into the SnackBarMaker
objects can independently satisfy their own
dependencies.
Scoped
If you try to inject something into an object with a
different scope, Dagger with give compilation error.
Scopes let objects “share” the same instance of anything in
the scope. ToolbarPresenters, IntentHolders etc.
Scopes cont’d
Scopes empower “activity singletons” that you
can share and not worry about reinstantiating
for each activity.
Dagger @ The New York Times
How we leveraged scope at The Times:
Inject activity intents into fragments 2 layers down
Create a toolbar presenter, each activity and its views get
access to the same presenter
Inject an alerthelper/snackbar util that can show alerts.
Dagger lets us decompose our activities
Dagger @ The New York Times
We can inject something that is being provided
by a module in library project.
A/B Module within A/B Project provides
injectable A/B manager
API project owns API module etc. Main Project
creates a component using all the modules
Dagger @ The New York Times
We can inject different implementations for
same interface spread across build variants
using a FlavorModule.
Amazon Flavor provides module with Amazon
Messaging
Google Flavor provides module with Google
Messaging
Sample Project
https://github.com/digitalbuddha/StoreDemo
Come work with me
http://developers.nytimes.com/careers

Contenu connexe

Tendances

PROMAND 2014 project structure
PROMAND 2014 project structurePROMAND 2014 project structure
PROMAND 2014 project structure
Alexey Buzdin
 

Tendances (20)

Sharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFSharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SF
 
Writing testable Android apps
Writing testable Android appsWriting testable Android apps
Writing testable Android apps
 
Dagger for dummies
Dagger for dummiesDagger for dummies
Dagger for dummies
 
Dagger 2 - Injeção de Dependência
Dagger 2 - Injeção de DependênciaDagger 2 - Injeção de Dependência
Dagger 2 - Injeção de Dependência
 
Android dev toolbox
Android dev toolboxAndroid dev toolbox
Android dev toolbox
 
PROMAND 2014 project structure
PROMAND 2014 project structurePROMAND 2014 project structure
PROMAND 2014 project structure
 
Lessons Learned Implementing a GraphQL API
Lessons Learned Implementing a GraphQL APILessons Learned Implementing a GraphQL API
Lessons Learned Implementing a GraphQL API
 
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and SearchNDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search
NDC Oslo 2019 - Indexing and searching NuGet.org with Azure Functions and Search
 
Ngrx meta reducers
Ngrx meta reducersNgrx meta reducers
Ngrx meta reducers
 
Grails Advanced
Grails Advanced Grails Advanced
Grails Advanced
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
Angular 2 introduction
Angular 2 introductionAngular 2 introduction
Angular 2 introduction
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized project
 
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1
Spring Boot Actuator 2.0 & Micrometer #jjug_ccc #ccc_a1
 
Angular - injection tokens & Custom libraries
Angular - injection tokens & Custom librariesAngular - injection tokens & Custom libraries
Angular - injection tokens & Custom libraries
 
Android Developer Toolbox 2017
Android Developer Toolbox 2017Android Developer Toolbox 2017
Android Developer Toolbox 2017
 
What’s new in Android JetPack
What’s new in Android JetPackWhat’s new in Android JetPack
What’s new in Android JetPack
 
Application Frameworks: The new kids on the block
Application Frameworks: The new kids on the blockApplication Frameworks: The new kids on the block
Application Frameworks: The new kids on the block
 
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
 
Test or Go Fishing - A guide on how to write better Swift for iOS
Test or Go Fishing - A guide on how to write better Swift for iOSTest or Go Fishing - A guide on how to write better Swift for iOS
Test or Go Fishing - A guide on how to write better Swift for iOS
 

Similaire à Sword fighting with Dagger GDG-NYC Jan 2016

Developing Useful APIs
Developing Useful APIsDeveloping Useful APIs
Developing Useful APIs
Dmitry Buzdin
 
Extending Groovys Swing User Interface in Builder to Build Richer Applications
Extending Groovys Swing User Interface in Builder to Build Richer ApplicationsExtending Groovys Swing User Interface in Builder to Build Richer Applications
Extending Groovys Swing User Interface in Builder to Build Richer Applications
James Williams
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
C.T.Co
 
Getting started with Verold and Three.js
Getting started with Verold and Three.jsGetting started with Verold and Three.js
Getting started with Verold and Three.js
Verold
 

Similaire à Sword fighting with Dagger GDG-NYC Jan 2016 (20)

Dependency Injection for Android
Dependency Injection for AndroidDependency Injection for Android
Dependency Injection for Android
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
 
Dependency injection using dagger2
Dependency injection using dagger2Dependency injection using dagger2
Dependency injection using dagger2
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applications
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
Android architecture
Android architecture Android architecture
Android architecture
 
Dagger 2 ppt
Dagger 2 pptDagger 2 ppt
Dagger 2 ppt
 
Testing Android apps based on Dagger and RxJava Droidcon UK
Testing Android apps based on Dagger and RxJava Droidcon UKTesting Android apps based on Dagger and RxJava Droidcon UK
Testing Android apps based on Dagger and RxJava Droidcon UK
 
[Ultracode Munich #4] Short introduction to the new Android build system incl...
[Ultracode Munich #4] Short introduction to the new Android build system incl...[Ultracode Munich #4] Short introduction to the new Android build system incl...
[Ultracode Munich #4] Short introduction to the new Android build system incl...
 
Developing Useful APIs
Developing Useful APIsDeveloping Useful APIs
Developing Useful APIs
 
Extending Groovys Swing User Interface in Builder to Build Richer Applications
Extending Groovys Swing User Interface in Builder to Build Richer ApplicationsExtending Groovys Swing User Interface in Builder to Build Richer Applications
Extending Groovys Swing User Interface in Builder to Build Richer Applications
 
React Native custom components
React Native custom componentsReact Native custom components
React Native custom components
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Di code steps
Di code stepsDi code steps
Di code steps
 
Getting started with Verold and Three.js
Getting started with Verold and Three.jsGetting started with Verold and Three.js
Getting started with Verold and Three.js
 
Infinum Android Talks #15 - Garfield Android Studio Plugin - Be Smart, Be Lazy
Infinum Android Talks #15 - Garfield Android Studio Plugin - Be Smart, Be LazyInfinum Android Talks #15 - Garfield Android Studio Plugin - Be Smart, Be Lazy
Infinum Android Talks #15 - Garfield Android Studio Plugin - Be Smart, Be Lazy
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Quick look at Design Patterns in Android Development
Quick look at Design Patterns in Android DevelopmentQuick look at Design Patterns in Android Development
Quick look at Design Patterns in Android Development
 
Guice2.0
Guice2.0Guice2.0
Guice2.0
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

Sword fighting with Dagger GDG-NYC Jan 2016

  • 1. Sword Fighting with Dagger Mike Nakhimovich Android Engineer NY Times
  • 2. What is Dagger? Dagger offers an alternative way to instantiate and manage your objects through Dependency Injection Dagger 2 open sourced by Google Dagger 1 – Square Guice – Google (Dagger v.0)
  • 3. Compile Time Annotation Processing (Fast) Superpowers Lazy Singleton Provider Why Dagger?
  • 4. In the Olden Days...
  • 5. Old Way public class RedditView { private RedditPresenter presenter; public RedditView(...) { Gson gson = new GsonBuilder().create(); RedditApi redditApi = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .build().create(RedditApi.class); RedditDAO redditDAO = new RedditDAO(redditApi); presenter=new RedditPresenter(redditDAO); }
  • 7. @Provides Gson provideGson() { } Create a Provider return new GsonBuilder().create(); }
  • 8. Modules A Module is a part of your application that provides implementations. @Module public class DataModule { } @Provides Gson provideGson() { return gsonBuilder.create();}
  • 9. Dependencies @Provides methods can have their own dependencies @Provides RedditApi provideRedditApi(Gson gson) { return new Retrofit.Builder() .addConverterFactory( GsonConverterFactory.create(gson)) .build().create(RedditApi.class); }
  • 10. Provides not necessary You can also annotate constructors directly to register public class RedditDAO { @Inject public RedditDAO(RedditApi api) { super(); } } Provided by Module
  • 12. Components A component is a part of your application that consumes functionality. Built from Module(s) @Component( modules = {DataModule.class}) public interface AppComponent { void inject(RedditView a); }
  • 13. Register with Component Activities/Services/Views register with an instance of a component public RedditView(Context context) { getComponent().inject(this); }
  • 14. Injection Fun Now you can inject any dependencies managed by the component. As a field As a Constructor Param
  • 15. Instantiating Dependencies Old Way RedditPresenter presenter; public RedditView(Context context) { super(context); Gson gson = new GsonBuilder().create(); RedditApi redditApi = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .build() .create(RedditApi.class); RedditDAO redditDAO = new RedditDAO(redditApi); presenter=new RedditPresenter(redditDAO); }
  • 16. Once RedditView registers itself with a component, Dagger will satisfy all managed dependencies with @Inject annotations @Inject RedditPresenter presenter; public RedditView(...) { getComponent().inject(this); } Instantiating Dependencies Dagger Way
  • 17. How does Dagger do it? A static DaggerAppComponent.builder() call creates a Builder instance; Builder creates an DaggerAppComponent instance; DaggerAppComponent creates a RedditView_MembersInjector instance; RedditView_MembersInjectorr uses RedditPresenter_Factory to instantiate RedditPresenter and injects it into RedditView. Just as fast as hand written code but with fewer errors
  • 18. Generated Code @Generated("dagger.internal.codegen.ComponentProcessor") public final class RedditPresenter_Factory implements Factory<RedditPresenter> { private final MembersInjector<RedditPresenter> membersInjector; public RedditPresenter_Factory(MembersInjector<RedditPresenter> membersInjector) { assert membersInjector != null; this.membersInjector = membersInjector; } @Override public RedditPresenter get() { RedditPresenter instance = new RedditPresenter(); membersInjector.injectMembers(instance); return instance; } public static Factory<RedditPresenter> create(MembersInjector<RedditPresenter> membersInjector) { return new RedditPresenter_Factory(membersInjector); } }
  • 19. Dependency Chain The Presenter has its own dependency public class RedditPresenter { @Inject RedditDAO dao; }
  • 20. Dependency Chain Which has its own dependency public class RedditDAO { private final RedditApi api; @Inject public RedditDAO(RedditApi api) { this.api = api; }
  • 21. Dagger Eliminates “Passing Through” Constructor Arguments
  • 22. Old Way RedditPresenter presenter; public RedditView(...) { super(context); Gson gson = new GsonBuilder().create(); RedditApi redditApi = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .build() .create(RedditApi.class); RedditDAO redditDAO = new RedditDAO(redditApi); presenter=new RedditPresenter(redditDAO); }
  • 23. Dagger Eliminates “Passing Through” Constructor Arguments Dagger Way: Inject ONLY the dependencies each object needs
  • 24. Type of Injections Dagger has a few types of injection: Direct Lazy Provider
  • 25. Direct When instance is created also create the dependency. public class RedditPresenter { @Inject RedditDAO dao; }
  • 26. Lazy Do not instantiate until .get() is called. public class RedditPresenter { @Inject Lazy<RedditDAO> dao; } Useful to keep startup time down
  • 27. Provider Provider<T> allows you to inject multiple instances of same object by calling .get() public class RedditPresenter { @Inject Provider<RedditDAO> dao; }
  • 28. Singletons Old Way public class MainActivity extends Activity { SharedPreferences pref; Gson gson; ServerAPI api; onCreate(...) { MyApp app = (MyApp)getContext().getApplicationContext(); pref = app.getSharedPreferences(); gson = app.getGson(); api = app.getApi(); Why is MYApp managing all singletons? :-(
  • 29. Singletons Dagger Way Define objects to be Singletons @Singleton @Provides Gson provideGson() { return gsonBuilder.create(); }
  • 30. Singletons Dagger Way Define objects to be Singletons @Singleton public class RedditDAO{ @Inject public RedditDAO() { }
  • 31. Singleton Management @Singleton = Single instance per Component @Singleton @Component( modules = {DataModule.class}) public interface AppComponent { void inject(RedditView a); }
  • 32. Scopes Singleton is a scope annotation @Scope @Documented @Retention(RUNTIME) public @interface Singleton {} We can create custom scope annotations
  • 33. Subcomponent Creating a Subcomponent with a scope @Subcomponent(modules = { ActivityModule.class}) @ActivityScope public interface ActivityComponent
  • 34. Subcomponent plussing your component into another component will inherit all objects
  • 35. Injecting Activities Components scoped (recreated) with each activity allows us to do silly things like injecting an activity into scoped objects: @ScopeActivity public class Toaster { @Inject Activity activity; private static void showToast() { Toast.makeText(activity, message).show(); }}
  • 36. Inject a Scoped Object @Inject SnackbarUtil snackbarUtil; there’s no need to pass activity into presenter and then into the SnackBarMaker objects can independently satisfy their own dependencies.
  • 37. Scoped If you try to inject something into an object with a different scope, Dagger with give compilation error. Scopes let objects “share” the same instance of anything in the scope. ToolbarPresenters, IntentHolders etc.
  • 38. Scopes cont’d Scopes empower “activity singletons” that you can share and not worry about reinstantiating for each activity.
  • 39. Dagger @ The New York Times How we leveraged scope at The Times: Inject activity intents into fragments 2 layers down Create a toolbar presenter, each activity and its views get access to the same presenter Inject an alerthelper/snackbar util that can show alerts.
  • 40. Dagger lets us decompose our activities
  • 41. Dagger @ The New York Times We can inject something that is being provided by a module in library project. A/B Module within A/B Project provides injectable A/B manager API project owns API module etc. Main Project creates a component using all the modules
  • 42. Dagger @ The New York Times We can inject different implementations for same interface spread across build variants using a FlavorModule. Amazon Flavor provides module with Amazon Messaging Google Flavor provides module with Google Messaging
  • 44. Come work with me http://developers.nytimes.com/careers