SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

Sharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFSharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFPierre-Yves Ricau
 
Writing testable Android apps
Writing testable Android appsWriting testable Android apps
Writing testable Android appsTomáš Kypta
 
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ênciaEdson Menegatti
 
Android dev toolbox
Android dev toolboxAndroid dev toolbox
Android dev toolboxShem Magnezi
 
PROMAND 2014 project structure
PROMAND 2014 project structurePROMAND 2014 project structure
PROMAND 2014 project structureAlexey Buzdin
 
Lessons Learned Implementing a GraphQL API
Lessons Learned Implementing a GraphQL APILessons Learned Implementing a GraphQL API
Lessons Learned Implementing a GraphQL APIDirk-Jan Rutten
 
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 SearchMaarten Balliauw
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksSamundra khatri
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized projectFabio Collini
 
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_a1Toshiaki Maki
 
Angular - injection tokens & Custom libraries
Angular - injection tokens & Custom librariesAngular - injection tokens & Custom libraries
Angular - injection tokens & Custom librariesEliran Eliassy
 
Android Developer Toolbox 2017
Android Developer Toolbox 2017Android Developer Toolbox 2017
Android Developer Toolbox 2017Shem Magnezi
 
What’s new in Android JetPack
What’s new in Android JetPackWhat’s new in Android JetPack
What’s new in Android JetPackHassan Abid
 
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 blockRichard Lord
 
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 Ali Parmaksiz
 
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 iOSPaul Ardeleanu
 

What's hot (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
 

Similar to Sword Fighting with Dagger Dependency Injection

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 2014First Tuesday Bergen
 
Dependency injection using dagger2
Dependency injection using dagger2Dependency injection using dagger2
Dependency injection using dagger2Javad Hashemi
 
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 applicationsMatteo Manchi
 
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 SideVisual Engineering
 
Android architecture
Android architecture Android architecture
Android architecture Trong-An Bui
 
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 UKFabio Collini
 
[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...BeMyApp
 
Developing Useful APIs
Developing Useful APIsDeveloping Useful APIs
Developing Useful APIsDmitry 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 ApplicationsJames Williams
 
React Native custom components
React Native custom componentsReact Native custom components
React Native custom componentsJeremy Grancher
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureC.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.jsVerold
 
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 LazyInfinum
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
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 DevelopmentConstantine Mars
 
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)Jose Manuel Pereira Garcia
 

Similar to Sword Fighting with Dagger Dependency Injection (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)
 

Recently uploaded

Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 

Recently uploaded (20)

Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 

Sword Fighting with Dagger Dependency Injection

  • 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