SlideShare a Scribd company logo
1 of 26
Download to read offline
Dagger 2 for Android
2018/2/6 John Lu
Agenda
* Assumed you know Dagger and have used it.
● About Dagger 2
○ Dagger 1
○ Dependency Graph
● Before Dagger 2.10
● Android Injector
○ What is the issue
○ How to use
● More advanced way for Android Injector
About Dagger 2 - Dagger 1
You might have heard about Spring[1]
and Guice[2]
they are former Dependency
Injection solution. But Dagger 1[3]
is a fast dependency injector for Java (of course
and Android) made by Square. It spends much more effort in compile time to
increase efficiency. (Now already deprecated, use Dagger2 so)
About Dagger 2 - Dependency Graph
I think to understand Dagger and use it properly let’s see a notion of Dependency
Injection[4]
and what it can conduct.
Design principle: Inverse of Control[5]
(Dependency Injection)
About Dagger 2 - Dependency Graph
Imagine dependency and provider are two nodes and there should be a directed
edge.
Once you have done of many dependency injections in your application it will
become
A B
About Dagger 2 - Dependency Graph
In Dagger 2[6]
, as you known @Component, @Module, and @Scope help you to
make a good dependency graph.
There is actual tool[7]
to generate image of Dagger dependency graph: https://github.com/dvdciri/daggraph
Component and Scope
Module
dependent
Before Dagger 2.10
Before the version 2.10 of Dagger 2, you can just say Dagger is a tool for
application based on Java. But from version 2.10[8]
Dagger starts providing some
stuffs that more easy to build your Android application with Dagger.
We are used to do old Dagger like this:
Before Dagger 2.10
We have to do inject for any class where needs dependency injection. Normally
we create Application Component and Subcomponent for Activity or Fragment.
If use after 2.10 you can just
AndroidInjection.inject(this); // Or even none of statement
Android Injector
Let’s say we are going to build a graph like this:
For instance, If app module provides `ApiService`,
we will have `ApiService` instance when we build
component which has app module.
Android Injector
@Component and @Component.Builder on AppComponent
Android Injector
@Component and @Component.Builder for building the top component.
AppComponent
AndroidSampleApp
Android Injector
@Component and @Component.Builder for building the top component.
AndroidSampleApp
@Provides
Application provideApplication();
or
@Inject Application app
or
@Provides
Context provideContext(Application app);
AppComponent
Android Injector
@SubComponent
In MainActivity, you need to request to inject
Anything you think are correct?
Android Injector - What is the issue
In MainActivity
Why AndroidSampleApp is being here? It looks violate some design principle,
right? Put a thing not related with the class. And you need to every time it sounds
not a good idea.
Android Injector - How to use it
You can install the Dagger as usual or you only want to use dagger.android[9]
module then you can
Android Injector - How to use it
Update the SubComponent extens AndroidInjector with your Activity.
It allow Android Injection Module knows where to inject.
Android Injector - How to use it
Provide a bind module to for Android Injection Module[10]
. (You can put all needed
to bind Activities here)
@Module
public abstract class ActivityBuilder {
@Binds
@IntoMap
@ActivityKey(MainActivity.class)
abstract AndroidInjector.Factory<? extends Activity> bindMainActivity(MainActivityComponent.Builder builder);
@Binds
@IntoMap
@ActivityKey(DetailActivity.class)
abstract AndroidInjector.Factory<? extends Activity> bindDetailActivity(DetailActivityComponent.Builder builder);
}
Android Injector - How to use it
Application implements a helper interface: HasActivityInjector
Android Injector - How to use it
Finally in your Activity, you can just
Then you can get your dependencies, no need to know Component or
SubComponent.
Android Injector - How to use it
For Fragment, as well as in Application you should implement a helper interface
on your Activity
In your Fragment, you can just:
More advanced way for Android Injector
Now you know the graph is like this
From: New Android Injector with Dagger 2 [11]
More advanced way for Android Injector
We can simplify the as you can see the SubComponents just like bridge between
Modules and Activities (If there is no other methods), so it can be like this with
@ContributesAndroidInjector
From: New Android Injector with Dagger 2 [11]
More advanced way for Android Injector
Rid SubComponents and bind methods in ActivityBuilder, then create the methods
instead and replace the modules declaration from SubComponent in the
annotation @ContributesAndroidInjector like this,
You can do the same for your fragments.
More advanced way for Android Injector
One more, remember in your Application there is DispatchingAndroidInjector
More advanced way for Android Injector
If your application can extend DaggerApplication then you don’t need to depend
on it
References
1. Spring: https://spring.io/
2. Guice: https://github.com/google/guice
3. Dagger 1: http://square.github.io/dagger/
4. Dependency Injection: https://en.wikipedia.org/wiki/Dependency_injection
5. Inverse of Control: https://en.wikipedia.org/wiki/Inversion_of_control
6. Dagger 2: https://google.github.io/dagger/
7. Daggraph: https://github.com/dvdciri/daggraph
8. Dagger 2.10; https://github.com/google/dagger/releases/tag/dagger-2.11
9. dagger.android: https://google.github.io/dagger/api/latest/dagger/android/package-summary.html
10. AndroidInjectionModule: https://google.github.io/dagger/api/latest/dagger/android/AndroidInjectionModule.html
11. New Android Injector with Dagger 2: https://medium.com/@iammert/new-android-injector-with-dagger-2-part-1-8baa60152abe

More Related Content

What's hot

Unit Testing Using Mockito in Android (1).pdf
Unit Testing Using Mockito in Android (1).pdfUnit Testing Using Mockito in Android (1).pdf
Unit Testing Using Mockito in Android (1).pdfKaty Slemon
 
Robotium at Android Only 2010-09-29
Robotium at Android Only 2010-09-29Robotium at Android Only 2010-09-29
Robotium at Android Only 2010-09-29Hugo Josefson
 
Lijie xia lx223809 monkeyrunner
Lijie xia lx223809 monkeyrunnerLijie xia lx223809 monkeyrunner
Lijie xia lx223809 monkeyrunnerLijie Xia
 
Testing android apps with espresso
Testing android apps with espressoTesting android apps with espresso
Testing android apps with espressoÉdipo Souza
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseUTC Fire & Security
 
Innovation Generation - The Mobile Meetup: Android Best Practices
Innovation Generation - The Mobile Meetup: Android Best PracticesInnovation Generation - The Mobile Meetup: Android Best Practices
Innovation Generation - The Mobile Meetup: Android Best PracticesSolstice Mobile Argentina
 
Xp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And MocksXp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And Mocksguillaumecarre
 
Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.Deepak Singhvi
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testingikhwanhayat
 
TDD with Visual Studio 2010
TDD with Visual Studio 2010TDD with Visual Studio 2010
TDD with Visual Studio 2010Stefano Paluello
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDDDror Helper
 
Unit testing
Unit testing Unit testing
Unit testing dubbu
 

What's hot (20)

Unit Testing Using Mockito in Android (1).pdf
Unit Testing Using Mockito in Android (1).pdfUnit Testing Using Mockito in Android (1).pdf
Unit Testing Using Mockito in Android (1).pdf
 
Robotium Tutorial
Robotium TutorialRobotium Tutorial
Robotium Tutorial
 
Android Test Automation Workshop
Android Test Automation WorkshopAndroid Test Automation Workshop
Android Test Automation Workshop
 
Robotium - sampath
Robotium - sampathRobotium - sampath
Robotium - sampath
 
Robotium at Android Only 2010-09-29
Robotium at Android Only 2010-09-29Robotium at Android Only 2010-09-29
Robotium at Android Only 2010-09-29
 
Lijie xia lx223809 monkeyrunner
Lijie xia lx223809 monkeyrunnerLijie xia lx223809 monkeyrunner
Lijie xia lx223809 monkeyrunner
 
Testing android apps with espresso
Testing android apps with espressoTesting android apps with espresso
Testing android apps with espresso
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
Innovation Generation - The Mobile Meetup: Android Best Practices
Innovation Generation - The Mobile Meetup: Android Best PracticesInnovation Generation - The Mobile Meetup: Android Best Practices
Innovation Generation - The Mobile Meetup: Android Best Practices
 
Xp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And MocksXp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And Mocks
 
Unit Testing in Android
Unit Testing in AndroidUnit Testing in Android
Unit Testing in Android
 
Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.
 
Testing In Java
Testing In JavaTesting In Java
Testing In Java
 
Unit test
Unit testUnit test
Unit test
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
TDD with Visual Studio 2010
TDD with Visual Studio 2010TDD with Visual Studio 2010
TDD with Visual Studio 2010
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Unit testing
Unit testing Unit testing
Unit testing
 
Unit Testing 101
Unit Testing 101Unit Testing 101
Unit Testing 101
 

Similar to Dagger for android

Android Dagger 2
Android  Dagger 2Android  Dagger 2
Android Dagger 2Sanket Shah
 
Creating the first app with android studio
Creating the first app with android studioCreating the first app with android studio
Creating the first app with android studioParinita03
 
Android architecture
Android architecture Android architecture
Android architecture Trong-An Bui
 
Easy job scheduling with android
Easy job scheduling with androidEasy job scheduling with android
Easy job scheduling with androidkirubhakarans2
 
Angular 14.pdf
Angular 14.pdfAngular 14.pdf
Angular 14.pdfSanesDm
 
Getting started with dagger 2
Getting started with dagger 2Getting started with dagger 2
Getting started with dagger 2Rodrigo Henriques
 
Installing android sdk on net beans
Installing android sdk on net beansInstalling android sdk on net beans
Installing android sdk on net beansAravindharamanan S
 
Angular2 with type script
Angular2 with type scriptAngular2 with type script
Angular2 with type scriptRavi Mone
 
How Android Architecture Components can Help You Improve Your App’s Design?
How Android Architecture Components can Help You Improve Your App’s Design?How Android Architecture Components can Help You Improve Your App’s Design?
How Android Architecture Components can Help You Improve Your App’s Design?Paul Cook
 
Angular kickstart slideshare
Angular kickstart   slideshareAngular kickstart   slideshare
Angular kickstart slideshareSaleemMalik52
 

Similar to Dagger for android (20)

Android Dagger 2
Android  Dagger 2Android  Dagger 2
Android Dagger 2
 
Android Dagger2
Android Dagger2Android Dagger2
Android Dagger2
 
Creating the first app with android studio
Creating the first app with android studioCreating the first app with android studio
Creating the first app with android studio
 
Android
AndroidAndroid
Android
 
Android session 2
Android session 2Android session 2
Android session 2
 
Android Study Jams - Session 1
Android Study Jams - Session 1Android Study Jams - Session 1
Android Study Jams - Session 1
 
Compose Camp - Session2.pdf
Compose Camp - Session2.pdfCompose Camp - Session2.pdf
Compose Camp - Session2.pdf
 
Android architecture
Android architecture Android architecture
Android architecture
 
Dagger2 Intro
Dagger2 IntroDagger2 Intro
Dagger2 Intro
 
Getting started with android studio
Getting started with android studioGetting started with android studio
Getting started with android studio
 
Easy job scheduling with android
Easy job scheduling with androidEasy job scheduling with android
Easy job scheduling with android
 
Angular 14.pdf
Angular 14.pdfAngular 14.pdf
Angular 14.pdf
 
Getting started with dagger 2
Getting started with dagger 2Getting started with dagger 2
Getting started with dagger 2
 
Installing android sdk on net beans
Installing android sdk on net beansInstalling android sdk on net beans
Installing android sdk on net beans
 
Angular2 with type script
Angular2 with type scriptAngular2 with type script
Angular2 with type script
 
How Android Architecture Components can Help You Improve Your App’s Design?
How Android Architecture Components can Help You Improve Your App’s Design?How Android Architecture Components can Help You Improve Your App’s Design?
How Android Architecture Components can Help You Improve Your App’s Design?
 
Android app development guide for freshers by ace web academy
Android app development guide for freshers  by ace web academyAndroid app development guide for freshers  by ace web academy
Android app development guide for freshers by ace web academy
 
How To Build and Deploy Android App Bundles.pdf
How To Build and Deploy Android App Bundles.pdfHow To Build and Deploy Android App Bundles.pdf
How To Build and Deploy Android App Bundles.pdf
 
Angular kickstart slideshare
Angular kickstart   slideshareAngular kickstart   slideshare
Angular kickstart slideshare
 
Angular
AngularAngular
Angular
 

More from Kan-Han (John) Lu

Working process and git branch strategy
Working process and git branch strategyWorking process and git branch strategy
Working process and git branch strategyKan-Han (John) Lu
 
Deep neural network for youtube recommendations
Deep neural network for youtube recommendationsDeep neural network for youtube recommendations
Deep neural network for youtube recommendationsKan-Han (John) Lu
 
Twitter as a personalizable information service ii
Twitter as a personalizable information service iiTwitter as a personalizable information service ii
Twitter as a personalizable information service iiKan-Han (John) Lu
 
Multimedia data minig and analytics sentiment analysis using social multimedia
Multimedia data minig and analytics sentiment analysis using social multimediaMultimedia data minig and analytics sentiment analysis using social multimedia
Multimedia data minig and analytics sentiment analysis using social multimediaKan-Han (John) Lu
 
ARM: Trusted Zone on Android
ARM: Trusted Zone on AndroidARM: Trusted Zone on Android
ARM: Trusted Zone on AndroidKan-Han (John) Lu
 
Android Training - Card Style
Android Training - Card StyleAndroid Training - Card Style
Android Training - Card StyleKan-Han (John) Lu
 
Android Training - View Pager
Android Training - View PagerAndroid Training - View Pager
Android Training - View PagerKan-Han (John) Lu
 
Android Training - Sliding Menu
Android Training - Sliding MenuAndroid Training - Sliding Menu
Android Training - Sliding MenuKan-Han (John) Lu
 
Android Training - Pull to Refresh
Android Training - Pull to RefreshAndroid Training - Pull to Refresh
Android Training - Pull to RefreshKan-Han (John) Lu
 
Code analyzer: FindBugs and PMD
Code analyzer: FindBugs and PMDCode analyzer: FindBugs and PMD
Code analyzer: FindBugs and PMDKan-Han (John) Lu
 
Android Training - Content Sharing
Android Training - Content SharingAndroid Training - Content Sharing
Android Training - Content SharingKan-Han (John) Lu
 
Android Training - Action Bar
Android Training - Action BarAndroid Training - Action Bar
Android Training - Action BarKan-Han (John) Lu
 

More from Kan-Han (John) Lu (20)

Android develop guideline
Android develop guidelineAndroid develop guideline
Android develop guideline
 
Working process and git branch strategy
Working process and git branch strategyWorking process and git branch strategy
Working process and git branch strategy
 
Deep neural network for youtube recommendations
Deep neural network for youtube recommendationsDeep neural network for youtube recommendations
Deep neural network for youtube recommendations
 
Cuda project paper
Cuda project paperCuda project paper
Cuda project paper
 
Twitter as a personalizable information service ii
Twitter as a personalizable information service iiTwitter as a personalizable information service ii
Twitter as a personalizable information service ii
 
Multimedia data minig and analytics sentiment analysis using social multimedia
Multimedia data minig and analytics sentiment analysis using social multimediaMultimedia data minig and analytics sentiment analysis using social multimedia
Multimedia data minig and analytics sentiment analysis using social multimedia
 
Android IPC: Binder
Android IPC: BinderAndroid IPC: Binder
Android IPC: Binder
 
ARM: Trusted Zone on Android
ARM: Trusted Zone on AndroidARM: Trusted Zone on Android
ARM: Trusted Zone on Android
 
Android Training - Card Style
Android Training - Card StyleAndroid Training - Card Style
Android Training - Card Style
 
Android Training - View Pager
Android Training - View PagerAndroid Training - View Pager
Android Training - View Pager
 
Android Training - Sliding Menu
Android Training - Sliding MenuAndroid Training - Sliding Menu
Android Training - Sliding Menu
 
Android Training - Pull to Refresh
Android Training - Pull to RefreshAndroid Training - Pull to Refresh
Android Training - Pull to Refresh
 
Java: Exception Handling
Java: Exception HandlingJava: Exception Handling
Java: Exception Handling
 
Dynamic Proxy by Java
Dynamic Proxy by JavaDynamic Proxy by Java
Dynamic Proxy by Java
 
Code analyzer: FindBugs and PMD
Code analyzer: FindBugs and PMDCode analyzer: FindBugs and PMD
Code analyzer: FindBugs and PMD
 
Android UI System
Android UI SystemAndroid UI System
Android UI System
 
Android Fragment
Android FragmentAndroid Fragment
Android Fragment
 
Android Training - Content Sharing
Android Training - Content SharingAndroid Training - Content Sharing
Android Training - Content Sharing
 
Android Training - Action Bar
Android Training - Action BarAndroid Training - Action Bar
Android Training - Action Bar
 
Explaination of angular
Explaination of angularExplaination of angular
Explaination of angular
 

Recently uploaded

Comprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfComprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfalene1
 
multiple access in wireless communication
multiple access in wireless communicationmultiple access in wireless communication
multiple access in wireless communicationpanditadesh123
 
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSneha Padhiar
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxRomil Mishra
 
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENTFUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENTSneha Padhiar
 
CS 3251 Programming in c all unit notes pdf
CS 3251 Programming in c all unit notes pdfCS 3251 Programming in c all unit notes pdf
CS 3251 Programming in c all unit notes pdfBalamuruganV28
 
Research Methodology for Engineering pdf
Research Methodology for Engineering pdfResearch Methodology for Engineering pdf
Research Methodology for Engineering pdfCaalaaAbdulkerim
 
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Sumanth A
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionMebane Rash
 
Robotics Group 10 (Control Schemes) cse.pdf
Robotics Group 10  (Control Schemes) cse.pdfRobotics Group 10  (Control Schemes) cse.pdf
Robotics Group 10 (Control Schemes) cse.pdfsahilsajad201
 
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Erbil Polytechnic University
 
Immutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdfImmutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdfDrew Moseley
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingBootNeck1
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxsiddharthjain2303
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptxmohitesoham12
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfChristianCDAM
 
Levelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodLevelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodManicka Mamallan Andavar
 
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHTEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHSneha Padhiar
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating SystemRashmi Bhat
 
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithmComputer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithmDeepika Walanjkar
 

Recently uploaded (20)

Comprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfComprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
 
multiple access in wireless communication
multiple access in wireless communicationmultiple access in wireless communication
multiple access in wireless communication
 
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptx
 
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENTFUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
 
CS 3251 Programming in c all unit notes pdf
CS 3251 Programming in c all unit notes pdfCS 3251 Programming in c all unit notes pdf
CS 3251 Programming in c all unit notes pdf
 
Research Methodology for Engineering pdf
Research Methodology for Engineering pdfResearch Methodology for Engineering pdf
Research Methodology for Engineering pdf
 
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of Action
 
Robotics Group 10 (Control Schemes) cse.pdf
Robotics Group 10  (Control Schemes) cse.pdfRobotics Group 10  (Control Schemes) cse.pdf
Robotics Group 10 (Control Schemes) cse.pdf
 
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
 
Immutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdfImmutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdf
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event Scheduling
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptx
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptx
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdf
 
Levelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodLevelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument method
 
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHTEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating System
 
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithmComputer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithm
 

Dagger for android

  • 1. Dagger 2 for Android 2018/2/6 John Lu
  • 2. Agenda * Assumed you know Dagger and have used it. ● About Dagger 2 ○ Dagger 1 ○ Dependency Graph ● Before Dagger 2.10 ● Android Injector ○ What is the issue ○ How to use ● More advanced way for Android Injector
  • 3. About Dagger 2 - Dagger 1 You might have heard about Spring[1] and Guice[2] they are former Dependency Injection solution. But Dagger 1[3] is a fast dependency injector for Java (of course and Android) made by Square. It spends much more effort in compile time to increase efficiency. (Now already deprecated, use Dagger2 so)
  • 4. About Dagger 2 - Dependency Graph I think to understand Dagger and use it properly let’s see a notion of Dependency Injection[4] and what it can conduct. Design principle: Inverse of Control[5] (Dependency Injection)
  • 5. About Dagger 2 - Dependency Graph Imagine dependency and provider are two nodes and there should be a directed edge. Once you have done of many dependency injections in your application it will become A B
  • 6. About Dagger 2 - Dependency Graph In Dagger 2[6] , as you known @Component, @Module, and @Scope help you to make a good dependency graph. There is actual tool[7] to generate image of Dagger dependency graph: https://github.com/dvdciri/daggraph Component and Scope Module dependent
  • 7. Before Dagger 2.10 Before the version 2.10 of Dagger 2, you can just say Dagger is a tool for application based on Java. But from version 2.10[8] Dagger starts providing some stuffs that more easy to build your Android application with Dagger. We are used to do old Dagger like this:
  • 8. Before Dagger 2.10 We have to do inject for any class where needs dependency injection. Normally we create Application Component and Subcomponent for Activity or Fragment. If use after 2.10 you can just AndroidInjection.inject(this); // Or even none of statement
  • 9. Android Injector Let’s say we are going to build a graph like this: For instance, If app module provides `ApiService`, we will have `ApiService` instance when we build component which has app module.
  • 10. Android Injector @Component and @Component.Builder on AppComponent
  • 11. Android Injector @Component and @Component.Builder for building the top component. AppComponent AndroidSampleApp
  • 12. Android Injector @Component and @Component.Builder for building the top component. AndroidSampleApp @Provides Application provideApplication(); or @Inject Application app or @Provides Context provideContext(Application app); AppComponent
  • 13. Android Injector @SubComponent In MainActivity, you need to request to inject Anything you think are correct?
  • 14. Android Injector - What is the issue In MainActivity Why AndroidSampleApp is being here? It looks violate some design principle, right? Put a thing not related with the class. And you need to every time it sounds not a good idea.
  • 15. Android Injector - How to use it You can install the Dagger as usual or you only want to use dagger.android[9] module then you can
  • 16. Android Injector - How to use it Update the SubComponent extens AndroidInjector with your Activity. It allow Android Injection Module knows where to inject.
  • 17. Android Injector - How to use it Provide a bind module to for Android Injection Module[10] . (You can put all needed to bind Activities here) @Module public abstract class ActivityBuilder { @Binds @IntoMap @ActivityKey(MainActivity.class) abstract AndroidInjector.Factory<? extends Activity> bindMainActivity(MainActivityComponent.Builder builder); @Binds @IntoMap @ActivityKey(DetailActivity.class) abstract AndroidInjector.Factory<? extends Activity> bindDetailActivity(DetailActivityComponent.Builder builder); }
  • 18. Android Injector - How to use it Application implements a helper interface: HasActivityInjector
  • 19. Android Injector - How to use it Finally in your Activity, you can just Then you can get your dependencies, no need to know Component or SubComponent.
  • 20. Android Injector - How to use it For Fragment, as well as in Application you should implement a helper interface on your Activity In your Fragment, you can just:
  • 21. More advanced way for Android Injector Now you know the graph is like this From: New Android Injector with Dagger 2 [11]
  • 22. More advanced way for Android Injector We can simplify the as you can see the SubComponents just like bridge between Modules and Activities (If there is no other methods), so it can be like this with @ContributesAndroidInjector From: New Android Injector with Dagger 2 [11]
  • 23. More advanced way for Android Injector Rid SubComponents and bind methods in ActivityBuilder, then create the methods instead and replace the modules declaration from SubComponent in the annotation @ContributesAndroidInjector like this, You can do the same for your fragments.
  • 24. More advanced way for Android Injector One more, remember in your Application there is DispatchingAndroidInjector
  • 25. More advanced way for Android Injector If your application can extend DaggerApplication then you don’t need to depend on it
  • 26. References 1. Spring: https://spring.io/ 2. Guice: https://github.com/google/guice 3. Dagger 1: http://square.github.io/dagger/ 4. Dependency Injection: https://en.wikipedia.org/wiki/Dependency_injection 5. Inverse of Control: https://en.wikipedia.org/wiki/Inversion_of_control 6. Dagger 2: https://google.github.io/dagger/ 7. Daggraph: https://github.com/dvdciri/daggraph 8. Dagger 2.10; https://github.com/google/dagger/releases/tag/dagger-2.11 9. dagger.android: https://google.github.io/dagger/api/latest/dagger/android/package-summary.html 10. AndroidInjectionModule: https://google.github.io/dagger/api/latest/dagger/android/AndroidInjectionModule.html 11. New Android Injector with Dagger 2: https://medium.com/@iammert/new-android-injector-with-dagger-2-part-1-8baa60152abe