SlideShare ist ein Scribd-Unternehmen logo
1 von 19
Dagger 2
DEPENDENCY INJECTION
(PART-1)
-SANKET SHAH
Introduction
Before starting with DI , Let’s understand the Coupling , Decoupling and
Cohesion.
Coupling :
Tight Coupling :
If two classes make calls to methods of each other then they are
tightly coupled, as changing one would mean having to
change the other.
Decoupling (Low Coupling / Lose Coupling):
Decoupling is the process of making something that was tightly
coupled less so, or not at all.
Cohesion :
Cohesion is the OO principle most closely associated with making sure
that a class is designed with a single
What is DI(Dependency Injection) ?
Introduction
The general concept behind dependency injection is called Inversion of Control.
According to this concept a class should not configure its dependencies statically
but should be configured from the outside.
A Java class has a dependency on another class, if it uses an instance of this class.
We call this a _class dependency.
Dependency injection can be performed on:
• The constructor of the class (construction injection)
• A field (field injection)
• The parameters of a method (method injection)
What is DI(Dependency Injection) ?
Quick Start On Dagger-2
Gradle Dependencies :
1. compile 'com.google.dagger:dagger:2.x'
2. annotationProcessor 'com.google.dagger:dagger-compiler:2.x' }
Application Class :
final AppComponent appComponent = DaggerAppComponent.builder()
.application(this)
.build();
// DebugLog.e("");
DaggerAutoInject.init(this, appComponent);
Quick Start On Dagger-2
Key Points
1. Module
2. Component
3. Scope
To make a class part of dagger object graph, you need to annotate
constructor of the class with Inject annotation. This can be done if you own
the class or creation of object is simple.
Quick Start On Dagger-2
Example :
@Singleton
public class Heater {
@Inject
public Heater() {
}
}
@Singleton
public class Thermosiphon {
private Heater heater;
@Inject
public Thermosiphon(Heater heater) {
this.heater = heater;
}
}
Quick Start On Dagger-2
Key Points
1. Component :
You cannot use Dagger without any of those, since they contain all the information. I
tend to call components the object graph—objects depending on objects depending on
other objects and so on. Every dependency is a requirement that has to be satisfied
before the dependent object can be created. Thinking of it as a graph thus makes for a
much more understandable picture.
Components know everything about object creation and every object that you want to
use will be delivered to you by a component in some way. I want to start talking about
single components and their usage.
Quick Start On Dagger-2
Key Points
1. Module (@module) :
As mentioned above, to make a class part of dagger object graph, you need to
annotate constructor of the class with Inject annotation. This can be done if you
own the class or creation of object is simple.
If you don’t own a class and you want it to be part of dagger object graph, since
constructor can’t be annotated with Inject annotation in this case, you need to
create a method which returns target class type and annotate the method with
@Provides.
@Provides methods are also useful for making classes, which can be instantiated
only using builder classes, to be part of dagger object graph.
Classes which are annotated with Module and contain @Provides annotated
methods are called modules in dagger. Provider methods in modules are used by
dagger to build object graph. Below is an example of Module class.
Quick Start On Dagger-2
Key Points
Example :
@Module
public class HeaterModule {
@Provides
@Singleton
Heater heater() {
return new Heater(); // if not using @Inject constructor
}
}
@Module
public class ThermosiphonModule {
@Provides
@Singleton
Thermosiphon thermosiphon(Heater heater) {
return new Thermosiphon(heater); // if not using @Inject constructor
}
}
Quick Start On Dagger-2
Key Points
2. Component :
Annotating constructors and fields with Inject is not enough to make
Dagger work. What is needed is an interface for your app’s main code to
get objects from dagger object graph. You need to define the interface
and annotate it with Component so that dagger will generate
implementation of the interface.
In the interface, you need to define methods which return the types you
are interested in. You can name these methods however you want, but
what is important is return type. Below is a component interface example.
Following section explains how to use components and its methods.
Quick Start On Dagger-2
Key Points
Example :
@Singleton
@Component // no modules
public interface SingletonComponent {
Thermosiphon thermosiphon();
Heater heater();
void inject(Something something);
}
Quick Start On Dagger-2
Key Points
3. Scope:
Singleton annotation is a dagger defined scope. You can use scope annotation on
class and provides-methods in modules to make those instances tied to that scope.
Scope allows you to group instances based on the life time of instances so that
once instances of a particular scope are no longer used, they can be removed more
memory.
For example, instances which are used throughout the application can have
application level scope; instances which are used during a user session can have
session level scope and instances which are used during a flow of task can have
activity level scope. This way instances belong to unneeded scope can be removed
from memory.
Quick Start On Dagger-2
Key Points
Example :
Creating Scope & Using Scope
@Scope
@Retention(value= RetentionPolicy.RUNTIME)
public @interface CouponFlowScope {
}
@CouponFlowScope
@Component(modules={CouponModule.class})
public interface CouponComponent {
public void inject(MainActivity mainActivity);
}
Quick Questions
1. What is APT ?
Answer:
The android-apt plugin assists in working with annotation processors in
combination with Android Studio. It has two purposes:
• Allow to configure a compile time only annotation processor as a
dependency, not including the artifact in the final APK or library
• Set up the source paths so that code that is generated from the annotation
processor is correctly picked up by Android Studio.
2. What is the user of DI in android ?
Answer :
Let say we want to make some tea. How would we do it and what do we need?
We need some boiled water, a clean mug, teabags, sugar and milk (at least
that’s what I put into mine). In order to make tea we need to provide all these
ingredients and we need to manage all these ourselves. We have to fill the kettle
with water and heat it up, get the milk from the refrigerator and get the rest.
Now assume that we can make tea, by simply asking someone else to do it for
us. Someone that knows how to do the tea just the way we want it. Would that
be better than making the tea ourselves? If yes, then welcome to dependency
injection.
Dependency injection is a framework that takes care of creating objects for us
without having to worry about providing the right ingredients so to say.
Quick Questions
3. What are the advantages of Dagger-2 uses ?
Answer:
• Simple access to shared implementations.
• Simple settings of complex dependencies. The big apps usually have
a lot of dependencies. Dagger 2 allows you to control all
dependences easy.
• Simple unit testing and integration testing. We will discuss it in the
article about testing with Dagger 2.
• “Local” singletons.
• Code generation. The received code is clear and available for
debugging.
• No obfuscation problems. Both Point 5 and 6 are advantage
properties of Dagger 2 in comparison with Dagger 1. Dagger 1
worked with reflection. That’s why there were problems with
performance, obfuscation, strange errors in runtime.
Quick Revision
 @Inject—base annotation whereby the “dependency is requested”
 @Module—classes which methods “provide dependencies”
 @Provide—methods inside @Module, which “tell Dagger how we want to build
and present a dependency“
 @Component—bridge between @Inject and @Module
 @Scope—enables to create global and local singletons
Quick Links
 https://medium.com/@harivigneshjayapalan/dagger-2-for-android-beginners-
introduction-be6580cb3edb
 https://google.github.io/dagger/
 http://www.vogella.com/tutorials/Dagger/article.html
 https://dzone.com/articles/an-introduction-to-dagger-2-android-di-part-1-3
THANK YOU !!

Weitere ähnliche Inhalte

Was ist angesagt?

[Android] DI in multimodule application
[Android] DI in multimodule application[Android] DI in multimodule application
[Android] DI in multimodule applicationOleg Mazhukin
 
Android application architecture
Android application architectureAndroid application architecture
Android application architectureRomain Rochegude
 
Using Dagger in a Clean Architecture project
Using Dagger in a Clean Architecture projectUsing Dagger in a Clean Architecture project
Using Dagger in a Clean Architecture projectFabio Collini
 
Say hello to react js - Day 1
Say hello to react js   - Day 1Say hello to react js   - Day 1
Say hello to react js - Day 1Smile Gupta
 
Reuse features in Android applications
Reuse features in Android applicationsReuse features in Android applications
Reuse features in Android applicationsRomain Rochegude
 
Presenter deck icenium hol
Presenter deck   icenium holPresenter deck   icenium hol
Presenter deck icenium holDhananjay Kumar
 
Say Hello to React day2 presentation
Say Hello to React   day2 presentationSay Hello to React   day2 presentation
Say Hello to React day2 presentationSmile Gupta
 
Java Constructor
Java ConstructorJava Constructor
Java ConstructorSoba Arjun
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJSKnoldus Inc.
 
Dicoding Developer Coaching #13: Android | Melakukan Testing secara Otomatis ...
Dicoding Developer Coaching #13: Android | Melakukan Testing secara Otomatis ...Dicoding Developer Coaching #13: Android | Melakukan Testing secara Otomatis ...
Dicoding Developer Coaching #13: Android | Melakukan Testing secara Otomatis ...DicodingEvent
 
Introduction to Google Guice
Introduction to Google GuiceIntroduction to Google Guice
Introduction to Google GuiceKnoldus Inc.
 
Constructor in Java - ITVoyagers
Constructor in Java - ITVoyagersConstructor in Java - ITVoyagers
Constructor in Java - ITVoyagersITVoyagers
 
Dependency Injection або Don’t call me, I’ll call you
Dependency Injection або Don’t call me, I’ll call youDependency Injection або Don’t call me, I’ll call you
Dependency Injection або Don’t call me, I’ll call youDmytro Mindra
 
Quick answers to Angular2+ Interview Questions
Quick answers to Angular2+ Interview QuestionsQuick answers to Angular2+ Interview Questions
Quick answers to Angular2+ Interview QuestionsLuis Martín Espino Rivera
 
Dependency Injection in Drupal 8
Dependency Injection in Drupal 8Dependency Injection in Drupal 8
Dependency Injection in Drupal 8valuebound
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsANKUSH CHAVAN
 
Introduction to angular 2
Introduction to angular 2Introduction to angular 2
Introduction to angular 2Dor Moshe
 

Was ist angesagt? (20)

[Android] DI in multimodule application
[Android] DI in multimodule application[Android] DI in multimodule application
[Android] DI in multimodule application
 
Android application architecture
Android application architectureAndroid application architecture
Android application architecture
 
Using Dagger in a Clean Architecture project
Using Dagger in a Clean Architecture projectUsing Dagger in a Clean Architecture project
Using Dagger in a Clean Architecture project
 
Say hello to react js - Day 1
Say hello to react js   - Day 1Say hello to react js   - Day 1
Say hello to react js - Day 1
 
Reuse features in Android applications
Reuse features in Android applicationsReuse features in Android applications
Reuse features in Android applications
 
Presenter deck icenium hol
Presenter deck   icenium holPresenter deck   icenium hol
Presenter deck icenium hol
 
Say Hello to React day2 presentation
Say Hello to React   day2 presentationSay Hello to React   day2 presentation
Say Hello to React day2 presentation
 
Java Constructor
Java ConstructorJava Constructor
Java Constructor
 
Google Guice
Google GuiceGoogle Guice
Google Guice
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
 
Di code steps
Di code stepsDi code steps
Di code steps
 
Dicoding Developer Coaching #13: Android | Melakukan Testing secara Otomatis ...
Dicoding Developer Coaching #13: Android | Melakukan Testing secara Otomatis ...Dicoding Developer Coaching #13: Android | Melakukan Testing secara Otomatis ...
Dicoding Developer Coaching #13: Android | Melakukan Testing secara Otomatis ...
 
Introduction to Google Guice
Introduction to Google GuiceIntroduction to Google Guice
Introduction to Google Guice
 
Constructor in Java - ITVoyagers
Constructor in Java - ITVoyagersConstructor in Java - ITVoyagers
Constructor in Java - ITVoyagers
 
Dependency Injection або Don’t call me, I’ll call you
Dependency Injection або Don’t call me, I’ll call youDependency Injection або Don’t call me, I’ll call you
Dependency Injection або Don’t call me, I’ll call you
 
React workshop
React workshopReact workshop
React workshop
 
Quick answers to Angular2+ Interview Questions
Quick answers to Angular2+ Interview QuestionsQuick answers to Angular2+ Interview Questions
Quick answers to Angular2+ Interview Questions
 
Dependency Injection in Drupal 8
Dependency Injection in Drupal 8Dependency Injection in Drupal 8
Dependency Injection in Drupal 8
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle Methods
 
Introduction to angular 2
Introduction to angular 2Introduction to angular 2
Introduction to angular 2
 

Ähnlich wie Android Dagger 2

Dependency injection using dagger 2
Dependency injection using dagger 2Dependency injection using dagger 2
Dependency injection using dagger 2Mahmoud El-Naggar
 
Angular2 with type script
Angular2 with type scriptAngular2 with type script
Angular2 with type scriptRavi Mone
 
Solid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven DesignSolid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven DesignIrwansyah Irwansyah
 
Introduction to dependency injection in Scala (Play)
Introduction to dependency injection in Scala (Play)Introduction to dependency injection in Scala (Play)
Introduction to dependency injection in Scala (Play)Knoldus Inc.
 
Test Driven Development:Unit Testing, Dependency Injection, Mocking
Test Driven Development:Unit Testing, Dependency Injection, MockingTest Driven Development:Unit Testing, Dependency Injection, Mocking
Test Driven Development:Unit Testing, Dependency Injection, Mockingmrjawright
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@Alex Borsuk
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2Knoldus Inc.
 
Django tutorial
Django tutorialDjango tutorial
Django tutorialKsd Che
 
Angular.ppt
Angular.pptAngular.ppt
Angular.pptMytrux1
 
Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2Alessandro Molina
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPTAjay Chimmani
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesWalking Tree Technologies
 
Software design principles - jinal desai
Software design principles - jinal desaiSoftware design principles - jinal desai
Software design principles - jinal desaijinaldesailive
 
Javascript design patterns
Javascript design patternsJavascript design patterns
Javascript design patternsGomathiNayagam S
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfKnoldus Inc.
 
Writing testable Android apps
Writing testable Android appsWriting testable Android apps
Writing testable Android appsTomáš Kypta
 

Ähnlich wie Android Dagger 2 (20)

Dependency injection using dagger 2
Dependency injection using dagger 2Dependency injection using dagger 2
Dependency injection using dagger 2
 
Angular2 with type script
Angular2 with type scriptAngular2 with type script
Angular2 with type script
 
Solid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven DesignSolid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven Design
 
Spring boot
Spring bootSpring boot
Spring boot
 
Introduction to dependency injection in Scala (Play)
Introduction to dependency injection in Scala (Play)Introduction to dependency injection in Scala (Play)
Introduction to dependency injection in Scala (Play)
 
Notepad tutorial
Notepad tutorialNotepad tutorial
Notepad tutorial
 
Test Driven Development:Unit Testing, Dependency Injection, Mocking
Test Driven Development:Unit Testing, Dependency Injection, MockingTest Driven Development:Unit Testing, Dependency Injection, Mocking
Test Driven Development:Unit Testing, Dependency Injection, Mocking
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
 
Django tutorial
Django tutorialDjango tutorial
Django tutorial
 
Dagger for android
Dagger for androidDagger for android
Dagger for android
 
Angular.ppt
Angular.pptAngular.ppt
Angular.ppt
 
Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2Rapid Prototyping with TurboGears2
Rapid Prototyping with TurboGears2
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree Technologies
 
Software design principles - jinal desai
Software design principles - jinal desaiSoftware design principles - jinal desai
Software design principles - jinal desai
 
Javascript design patterns
Javascript design patternsJavascript design patterns
Javascript design patterns
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
 
Writing testable Android apps
Writing testable Android appsWriting testable Android apps
Writing testable Android apps
 

Kürzlich hochgeladen

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 

Kürzlich hochgeladen (20)

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 

Android Dagger 2

  • 2. Introduction Before starting with DI , Let’s understand the Coupling , Decoupling and Cohesion. Coupling : Tight Coupling : If two classes make calls to methods of each other then they are tightly coupled, as changing one would mean having to change the other. Decoupling (Low Coupling / Lose Coupling): Decoupling is the process of making something that was tightly coupled less so, or not at all. Cohesion : Cohesion is the OO principle most closely associated with making sure that a class is designed with a single What is DI(Dependency Injection) ?
  • 3.
  • 4. Introduction The general concept behind dependency injection is called Inversion of Control. According to this concept a class should not configure its dependencies statically but should be configured from the outside. A Java class has a dependency on another class, if it uses an instance of this class. We call this a _class dependency. Dependency injection can be performed on: • The constructor of the class (construction injection) • A field (field injection) • The parameters of a method (method injection) What is DI(Dependency Injection) ?
  • 5. Quick Start On Dagger-2 Gradle Dependencies : 1. compile 'com.google.dagger:dagger:2.x' 2. annotationProcessor 'com.google.dagger:dagger-compiler:2.x' } Application Class : final AppComponent appComponent = DaggerAppComponent.builder() .application(this) .build(); // DebugLog.e(""); DaggerAutoInject.init(this, appComponent);
  • 6. Quick Start On Dagger-2 Key Points 1. Module 2. Component 3. Scope To make a class part of dagger object graph, you need to annotate constructor of the class with Inject annotation. This can be done if you own the class or creation of object is simple.
  • 7. Quick Start On Dagger-2 Example : @Singleton public class Heater { @Inject public Heater() { } } @Singleton public class Thermosiphon { private Heater heater; @Inject public Thermosiphon(Heater heater) { this.heater = heater; } }
  • 8. Quick Start On Dagger-2 Key Points 1. Component : You cannot use Dagger without any of those, since they contain all the information. I tend to call components the object graph—objects depending on objects depending on other objects and so on. Every dependency is a requirement that has to be satisfied before the dependent object can be created. Thinking of it as a graph thus makes for a much more understandable picture. Components know everything about object creation and every object that you want to use will be delivered to you by a component in some way. I want to start talking about single components and their usage.
  • 9. Quick Start On Dagger-2 Key Points 1. Module (@module) : As mentioned above, to make a class part of dagger object graph, you need to annotate constructor of the class with Inject annotation. This can be done if you own the class or creation of object is simple. If you don’t own a class and you want it to be part of dagger object graph, since constructor can’t be annotated with Inject annotation in this case, you need to create a method which returns target class type and annotate the method with @Provides. @Provides methods are also useful for making classes, which can be instantiated only using builder classes, to be part of dagger object graph. Classes which are annotated with Module and contain @Provides annotated methods are called modules in dagger. Provider methods in modules are used by dagger to build object graph. Below is an example of Module class.
  • 10. Quick Start On Dagger-2 Key Points Example : @Module public class HeaterModule { @Provides @Singleton Heater heater() { return new Heater(); // if not using @Inject constructor } } @Module public class ThermosiphonModule { @Provides @Singleton Thermosiphon thermosiphon(Heater heater) { return new Thermosiphon(heater); // if not using @Inject constructor } }
  • 11. Quick Start On Dagger-2 Key Points 2. Component : Annotating constructors and fields with Inject is not enough to make Dagger work. What is needed is an interface for your app’s main code to get objects from dagger object graph. You need to define the interface and annotate it with Component so that dagger will generate implementation of the interface. In the interface, you need to define methods which return the types you are interested in. You can name these methods however you want, but what is important is return type. Below is a component interface example. Following section explains how to use components and its methods.
  • 12. Quick Start On Dagger-2 Key Points Example : @Singleton @Component // no modules public interface SingletonComponent { Thermosiphon thermosiphon(); Heater heater(); void inject(Something something); }
  • 13. Quick Start On Dagger-2 Key Points 3. Scope: Singleton annotation is a dagger defined scope. You can use scope annotation on class and provides-methods in modules to make those instances tied to that scope. Scope allows you to group instances based on the life time of instances so that once instances of a particular scope are no longer used, they can be removed more memory. For example, instances which are used throughout the application can have application level scope; instances which are used during a user session can have session level scope and instances which are used during a flow of task can have activity level scope. This way instances belong to unneeded scope can be removed from memory.
  • 14. Quick Start On Dagger-2 Key Points Example : Creating Scope & Using Scope @Scope @Retention(value= RetentionPolicy.RUNTIME) public @interface CouponFlowScope { } @CouponFlowScope @Component(modules={CouponModule.class}) public interface CouponComponent { public void inject(MainActivity mainActivity); }
  • 15. Quick Questions 1. What is APT ? Answer: The android-apt plugin assists in working with annotation processors in combination with Android Studio. It has two purposes: • Allow to configure a compile time only annotation processor as a dependency, not including the artifact in the final APK or library • Set up the source paths so that code that is generated from the annotation processor is correctly picked up by Android Studio. 2. What is the user of DI in android ? Answer : Let say we want to make some tea. How would we do it and what do we need? We need some boiled water, a clean mug, teabags, sugar and milk (at least that’s what I put into mine). In order to make tea we need to provide all these ingredients and we need to manage all these ourselves. We have to fill the kettle with water and heat it up, get the milk from the refrigerator and get the rest. Now assume that we can make tea, by simply asking someone else to do it for us. Someone that knows how to do the tea just the way we want it. Would that be better than making the tea ourselves? If yes, then welcome to dependency injection. Dependency injection is a framework that takes care of creating objects for us without having to worry about providing the right ingredients so to say.
  • 16. Quick Questions 3. What are the advantages of Dagger-2 uses ? Answer: • Simple access to shared implementations. • Simple settings of complex dependencies. The big apps usually have a lot of dependencies. Dagger 2 allows you to control all dependences easy. • Simple unit testing and integration testing. We will discuss it in the article about testing with Dagger 2. • “Local” singletons. • Code generation. The received code is clear and available for debugging. • No obfuscation problems. Both Point 5 and 6 are advantage properties of Dagger 2 in comparison with Dagger 1. Dagger 1 worked with reflection. That’s why there were problems with performance, obfuscation, strange errors in runtime.
  • 17. Quick Revision  @Inject—base annotation whereby the “dependency is requested”  @Module—classes which methods “provide dependencies”  @Provide—methods inside @Module, which “tell Dagger how we want to build and present a dependency“  @Component—bridge between @Inject and @Module  @Scope—enables to create global and local singletons
  • 18. Quick Links  https://medium.com/@harivigneshjayapalan/dagger-2-for-android-beginners- introduction-be6580cb3edb  https://google.github.io/dagger/  http://www.vogella.com/tutorials/Dagger/article.html  https://dzone.com/articles/an-introduction-to-dagger-2-android-di-part-1-3