SlideShare ist ein Scribd-Unternehmen logo
1 von 46
Downloaden Sie, um offline zu lesen
Taipei
Jintin
Dagger vs koin
Designed for the mobile
generation
● Snap, list, sell
● Private chat
● A.I. assisted selling
● Personalised content
What is Dependency Injection?
public class Twitter {
public void getFeeds() {
TwitterApi api = new TwitterApi();
api.getFeeds();
}
}
public class TwitterApi {
public void getFeeds () {
HttpClient httpClient = new HttpClient();
httpClient.connect("http://xxx.com")
}
}
public class Twitter {
public void getFeeds() {
TwitterApi api = new TwitterApi();
api.getFeeds();
}
}
public class TwitterApi {
public void getFeeds () {
HttpClient httpClient = new HttpClient();
httpClient.connect("http://xxx.com")
}
}
What’s the problem now?
● New is evil
● High coupling
● Hard to replace
● Hard to test
Dependency Injection
Dependency injection is basically providing
the objects that an object needs (its
dependencies) instead of having it construct
them itself.
How to Inject Object?
● Constructor Injection
● Method Injection
● Field Injection
public class Twitter {
public void getFeeds() {
TwitterApi api = new TwitterApi();
api.getFeeds();
}
}
public class TwitterApi {
public void getFeeds () {
HttpClient httpClient = new HttpClient();
httpClient.connect("http://xxx.com")
}
}
public class Twitter {
public void getFeeds(TwitterApi api) {
api.getFeeds();
}
}
public class TwitterApi {
HttpClient httpClient;
public TwitterApi(HttpClient httpClient) {
this.httpClient = httpClient;
}
}
What’s the problem now?
● Hard to use
● Manage dependency graph is a mess
● Dagger is the rescue
What is Dagger?
Dagger 2
● Dependency Injection tool
● Simple Annotation structure
● Readable generated code
● No reflection (fast)
● No runtime error
● Proguard friendly
● Pure Java
● https://github.com/google/dagger
● https://android.jlelse.eu/dagger-2-c00f31decda5
Annotation Processing
● Annotate in source code
● Start compile
● Read Annotation and relevant data
● Generate code under build folder
● Compile finish
● https://medium.com/@jintin/annotation-pr
ocessing-in-java-3621cb05343a
Annotations in Dagger2
● @Provides
● @Module
● @Component
● @Inject (in Java)
● @Qualifier (@Named)
● @Scope (@Singleton)
Bee Honey
Lemon
// Object class
class Lemon
class Bee
class Honey(var bee: Bee)
class HoneyLemonade
@Inject
constructor(var honey: Honey, var lemon: Lemon)
@Provides
Lemon provideLemon() {
return new Lemon();
}
@Provides
Honey provideHoney(Bee bee) {
return new Honey(bee);
}
@Provides
Bee provideBee() {
return new Bee();
}
@Module
public class DrinkModule {
@Provides
Lemon provideLemon() {...}
@Provides
Honey provideHoney(Bee bee) {...}
@Provides
Bee provideBee() {...}
}
@Component(modules = {DrinkModule.class})
public interface DrinkComponent {
HoneyLemonade drink();
void inject(MainActivity activity);
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DrinkComponent co = DaggerDrinkComponent.create();
HoneyLemonade drink = co.drink();
}
}
public class MainActivity extends AppCompatActivity {
@Inject
HoneyLemonade drink;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DrinkComponent co = DaggerDrinkComponent.create();
co.inject(this);
}
}
Recap
● Provides: provide dependency
● Modules: group Provides
● Component: The relation graph
● Inject: Identifier for inject
Other feature
● Qualifier: Named...
● Scope: Singleton...
● Subcomponent / includes
● Lazy / Provider...
Demo
What is koin?
koin
● Service locator by Kotlin DSL
● No code generation
● No reflection
● No compile time overhead
● Pure Kotlin
● https://github.com/InsertKoinIO/koin
Service locator
The service locator pattern is a design pattern
used in software development to encapsulate the
processes involved in obtaining a service with a
strong abstraction layer.
Object Locator
Lemon
Honey
Kotlin DSL
● Function literals with receiver
● Describe data structure
● Like Anko, ktor
// HTML DSL
val result =
html {
head {
title {+"XML encoding with Kotlin"}
}
body {
h1 {+"XML encoding with Kotlin"}
p {+"this format can be used"}
a(href = "http://kotlinlang.org") {+"Kotlin"}
}
}
fun html(init: HTML.() -> Unit): HTML {
val html = HTML()
html.init()
return html
}
fun body(init: Body.() -> Unit) : Body {
val body = Body()
body.init()
return body
}
koin DSL
● Module - create a Koin Module
● Factory - provide a factory bean definition
● Single - provide a singleton bean definition
(also aliased as bean)
● Get - resolve a component dependency
// gradle install
dependencies {
// Koin for Android
compile 'org.koin:koin-android:1.0.2'
// or Koin for Lifecycle scoping
compile 'org.koin:koin-android-scope:1.0.2'
// or Koin for Android Architecture ViewModel
compile 'org.koin:koin-android-viewmodel:1.0.2'
}
// Object class
class Bee
class Honey(var bee: Bee)
class Lemon
class HoneyLemonade(var honey: Honey,
var lemon: Lemon)
class MyApplication : Application() {
override fun onCreate(){
super.onCreate()
// start Koin!
startKoin(this, listOf(myModule))
}
}
val myModule = module {
single { Bee() }
single { Honey(get()) }
single { Lemon() }
single { HoneyLemonade(get(), get()) }
}
// How get() work? reified
inline fun <reified T : Any> get(
name: String = "",
scopeId: String? = null,
noinline parameters: ParameterDefinition = ...
): T {
val scope: Scope? = scopeId?.let {
koinContext.getScope(scopeId)
}
return koinContext.get(name, scope, parameters)
}
reified function
● Work with inline
● Can access actual type T
● After compile T will replace with actual type
class MyActivity() : AppCompatActivity() {
val drink : HoneyLemonade by inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val drink : HoneyLemonade = get()
}
}
// How inject(), get() work?
inline fun <reified T : Any> ComponentCallbacks.inject(
name: String = "",
scope: Scope? = null,
noinline parameters: ParameterDefinition = ...
) = lazy { get<T>(name, scope, parameters) }
inline fun <reified T : Any> ComponentCallbacks.get(
name: String = "",
scope: Scope? = null,
noinline parameters: ParameterDefinition = ...
): T = getKoin().get(name, scope, parameters)
// What is ComponentCallbacks btw?
Demo
Dagger vs koin
Dagger
● Pros:
○ + Pure Java
○ + Stable, flexible, powerful
○ + No Runtime error
○ + Fast in Runtime
● Cons:
○ - Compile overhead
○ - Hard to learn
koin
● Pros:
○ + No Annotation processing
○ + Easy to learn/setup
● Cons:
○ - Hard to replace/remove
○ - Test in its env
○ - Error in Runtime
“you and only you are responsible
for your life choices and decisions”
- Robert T. Kiyosaki
Jintin
Taipei
Thank you!

Weitere ähnliche Inhalte

Was ist angesagt?

WordPress plugin #2
WordPress plugin #2WordPress plugin #2
WordPress plugin #2giwoolee
 
Sword fighting with Dagger GDG-NYC Jan 2016
 Sword fighting with Dagger GDG-NYC Jan 2016 Sword fighting with Dagger GDG-NYC Jan 2016
Sword fighting with Dagger GDG-NYC Jan 2016Mike Nakhimovich
 
Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6Ray Ploski
 
Practical Protocol-Oriented-Programming
Practical Protocol-Oriented-ProgrammingPractical Protocol-Oriented-Programming
Practical Protocol-Oriented-ProgrammingNatasha Murashev
 
Make XCUITest Great Again
Make XCUITest Great AgainMake XCUITest Great Again
Make XCUITest Great AgainKenneth Poon
 
Kotlin Delegates in practice - Kotlin community conf
Kotlin Delegates in practice - Kotlin community confKotlin Delegates in practice - Kotlin community conf
Kotlin Delegates in practice - Kotlin community confFabio Collini
 
Building maintainable app #droidconzg
Building maintainable app #droidconzgBuilding maintainable app #droidconzg
Building maintainable app #droidconzgKristijan Jurković
 
Kotlin delegates in practice - Kotlin Everywhere Stockholm
Kotlin delegates in practice - Kotlin Everywhere StockholmKotlin delegates in practice - Kotlin Everywhere Stockholm
Kotlin delegates in practice - Kotlin Everywhere StockholmFabio Collini
 
Dependency Injection with CDI in 15 minutes
Dependency Injection with CDI in 15 minutesDependency Injection with CDI in 15 minutes
Dependency Injection with CDI in 15 minutesAntonio Goncalves
 
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
 
What’s new in Android JetPack
What’s new in Android JetPackWhat’s new in Android JetPack
What’s new in Android JetPackHassan Abid
 
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
 
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
 
Aggregation and Awareness or How to Reduce the Amount of your FrontEnd Code ...
Aggregation and Awareness or How to Reduce the Amount of  your FrontEnd Code ...Aggregation and Awareness or How to Reduce the Amount of  your FrontEnd Code ...
Aggregation and Awareness or How to Reduce the Amount of your FrontEnd Code ...ISS Art, LLC
 
Improving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesImproving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesHassan Abid
 

Was ist angesagt? (20)

Angular2 + rxjs
Angular2 + rxjsAngular2 + rxjs
Angular2 + rxjs
 
WordPress plugin #2
WordPress plugin #2WordPress plugin #2
WordPress plugin #2
 
Sword fighting with Dagger GDG-NYC Jan 2016
 Sword fighting with Dagger GDG-NYC Jan 2016 Sword fighting with Dagger GDG-NYC Jan 2016
Sword fighting with Dagger GDG-NYC Jan 2016
 
Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6
 
Practical Protocol-Oriented-Programming
Practical Protocol-Oriented-ProgrammingPractical Protocol-Oriented-Programming
Practical Protocol-Oriented-Programming
 
Make XCUITest Great Again
Make XCUITest Great AgainMake XCUITest Great Again
Make XCUITest Great Again
 
Kotlin Delegates in practice - Kotlin community conf
Kotlin Delegates in practice - Kotlin community confKotlin Delegates in practice - Kotlin community conf
Kotlin Delegates in practice - Kotlin community conf
 
Building maintainable app #droidconzg
Building maintainable app #droidconzgBuilding maintainable app #droidconzg
Building maintainable app #droidconzg
 
Kotlin delegates in practice - Kotlin Everywhere Stockholm
Kotlin delegates in practice - Kotlin Everywhere StockholmKotlin delegates in practice - Kotlin Everywhere Stockholm
Kotlin delegates in practice - Kotlin Everywhere Stockholm
 
Dependency Injection with CDI in 15 minutes
Dependency Injection with CDI in 15 minutesDependency Injection with CDI in 15 minutes
Dependency Injection with CDI in 15 minutes
 
Open sourcing the store
Open sourcing the storeOpen sourcing the store
Open sourcing the store
 
Sharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFSharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SF
 
Angular modules in depth
Angular modules in depthAngular modules in depth
Angular modules in depth
 
What’s new in Android JetPack
What’s new in Android JetPackWhat’s new in Android JetPack
What’s new in Android JetPack
 
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
 
Building maintainable app
Building maintainable appBuilding maintainable app
Building maintainable app
 
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
 
Aggregation and Awareness or How to Reduce the Amount of your FrontEnd Code ...
Aggregation and Awareness or How to Reduce the Amount of  your FrontEnd Code ...Aggregation and Awareness or How to Reduce the Amount of  your FrontEnd Code ...
Aggregation and Awareness or How to Reduce the Amount of your FrontEnd Code ...
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
 
Improving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesImproving app performance with Kotlin Coroutines
Improving app performance with Kotlin Coroutines
 

Ähnlich wie Dagger 2 vs koin

Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Python Ireland
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejugrobbiev
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 KotlinVMware Tanzu
 
Introduction to Spring Boot.pdf
Introduction to Spring Boot.pdfIntroduction to Spring Boot.pdf
Introduction to Spring Boot.pdfShaiAlmog1
 
Connecting to a Webservice.pdf
Connecting to a Webservice.pdfConnecting to a Webservice.pdf
Connecting to a Webservice.pdfShaiAlmog1
 
Maintaining a dependency graph with weaver
Maintaining a dependency graph with weaverMaintaining a dependency graph with weaver
Maintaining a dependency graph with weaverScribd
 
Page Objects Done Right - selenium conference 2014
Page Objects Done Right - selenium conference 2014Page Objects Done Right - selenium conference 2014
Page Objects Done Right - selenium conference 2014Oren Rubin
 
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
 
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...Naresha K
 
How to code to code less
How to code to code lessHow to code to code less
How to code to code lessAnton Novikau
 
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
 
Mastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin EdelsonMastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin EdelsonAEM HUB
 
Mastering the Sling Rewriter
Mastering the Sling RewriterMastering the Sling Rewriter
Mastering the Sling RewriterJustin Edelson
 

Ähnlich wie Dagger 2 vs koin (20)

Android workshop
Android workshopAndroid workshop
Android workshop
 
Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)
 
Vaadin7
Vaadin7Vaadin7
Vaadin7
 
Introduction to-java
Introduction to-javaIntroduction to-java
Introduction to-java
 
Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++
 
Vaadin 7
Vaadin 7Vaadin 7
Vaadin 7
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejug
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
 
Introduction to Spring Boot.pdf
Introduction to Spring Boot.pdfIntroduction to Spring Boot.pdf
Introduction to Spring Boot.pdf
 
Connecting to a Webservice.pdf
Connecting to a Webservice.pdfConnecting to a Webservice.pdf
Connecting to a Webservice.pdf
 
Maintaining a dependency graph with weaver
Maintaining a dependency graph with weaverMaintaining a dependency graph with weaver
Maintaining a dependency graph with weaver
 
Page Objects Done Right - selenium conference 2014
Page Objects Done Right - selenium conference 2014Page Objects Done Right - selenium conference 2014
Page Objects Done Right - selenium conference 2014
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
Day 5
Day 5Day 5
Day 5
 
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
 
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
 
How to code to code less
How to code to code lessHow to code to code less
How to code to code less
 
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)
 
Mastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin EdelsonMastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin Edelson
 
Mastering the Sling Rewriter
Mastering the Sling RewriterMastering the Sling Rewriter
Mastering the Sling Rewriter
 

Mehr von Jintin Lin

Annotation Processing
Annotation ProcessingAnnotation Processing
Annotation ProcessingJintin Lin
 
我的開源之旅
我的開源之旅我的開源之旅
我的開源之旅Jintin Lin
 
數學系的資訊人生
數學系的資訊人生數學系的資訊人生
數學系的資訊人生Jintin Lin
 
Instant app Intro
Instant app IntroInstant app Intro
Instant app IntroJintin Lin
 
KVO implementation
KVO implementationKVO implementation
KVO implementationJintin Lin
 
iOS NotificationCenter intro
iOS NotificationCenter introiOS NotificationCenter intro
iOS NotificationCenter introJintin Lin
 
App design guide
App design guideApp design guide
App design guideJintin Lin
 
Swimat - Swift formatter
Swimat - Swift formatterSwimat - Swift formatter
Swimat - Swift formatterJintin Lin
 
Swift Tutorial 2
Swift Tutorial  2Swift Tutorial  2
Swift Tutorial 2Jintin Lin
 
Swift Tutorial 1
Swift Tutorial 1Swift Tutorial 1
Swift Tutorial 1Jintin Lin
 
Realism vs Flat design
Realism vs Flat designRealism vs Flat design
Realism vs Flat designJintin Lin
 
Android Service Intro
Android Service IntroAndroid Service Intro
Android Service IntroJintin Lin
 

Mehr von Jintin Lin (17)

KSP intro
KSP introKSP intro
KSP intro
 
Annotation Processing
Annotation ProcessingAnnotation Processing
Annotation Processing
 
我的開源之旅
我的開源之旅我的開源之旅
我的開源之旅
 
ButterKnife
ButterKnifeButterKnife
ButterKnife
 
數學系的資訊人生
數學系的資訊人生數學系的資訊人生
數學系的資訊人生
 
Instant app Intro
Instant app IntroInstant app Intro
Instant app Intro
 
KVO implementation
KVO implementationKVO implementation
KVO implementation
 
iOS NotificationCenter intro
iOS NotificationCenter introiOS NotificationCenter intro
iOS NotificationCenter intro
 
App design guide
App design guideApp design guide
App design guide
 
J霧霾
J霧霾J霧霾
J霧霾
 
transai
transaitransai
transai
 
Swimat - Swift formatter
Swimat - Swift formatterSwimat - Swift formatter
Swimat - Swift formatter
 
Swift Tutorial 2
Swift Tutorial  2Swift Tutorial  2
Swift Tutorial 2
 
Swift Tutorial 1
Swift Tutorial 1Swift Tutorial 1
Swift Tutorial 1
 
Andle
AndleAndle
Andle
 
Realism vs Flat design
Realism vs Flat designRealism vs Flat design
Realism vs Flat design
 
Android Service Intro
Android Service IntroAndroid Service Intro
Android Service Intro
 

Kürzlich hochgeladen

Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsvanyagupta248
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiessarkmank1
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxmaisarahman1
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARKOUSTAV SARKAR
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Call Girls Mumbai
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptxrouholahahmadi9876
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdfAldoGarca30
 
Moment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilMoment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilVinayVitekari
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdfKamal Acharya
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksMagic Marks
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxMuhammadAsimMuhammad6
 
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...vershagrag
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...drmkjayanthikannan
 
Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxpritamlangde
 

Kürzlich hochgeladen (20)

Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Moment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilMoment Distribution Method For Btech Civil
Moment Distribution Method For Btech Civil
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic Marks
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptx
 

Dagger 2 vs koin

  • 2. Designed for the mobile generation ● Snap, list, sell ● Private chat ● A.I. assisted selling ● Personalised content
  • 3. What is Dependency Injection?
  • 4. public class Twitter { public void getFeeds() { TwitterApi api = new TwitterApi(); api.getFeeds(); } } public class TwitterApi { public void getFeeds () { HttpClient httpClient = new HttpClient(); httpClient.connect("http://xxx.com") } }
  • 5. public class Twitter { public void getFeeds() { TwitterApi api = new TwitterApi(); api.getFeeds(); } } public class TwitterApi { public void getFeeds () { HttpClient httpClient = new HttpClient(); httpClient.connect("http://xxx.com") } }
  • 6. What’s the problem now? ● New is evil ● High coupling ● Hard to replace ● Hard to test
  • 7. Dependency Injection Dependency injection is basically providing the objects that an object needs (its dependencies) instead of having it construct them itself.
  • 8. How to Inject Object? ● Constructor Injection ● Method Injection ● Field Injection
  • 9. public class Twitter { public void getFeeds() { TwitterApi api = new TwitterApi(); api.getFeeds(); } } public class TwitterApi { public void getFeeds () { HttpClient httpClient = new HttpClient(); httpClient.connect("http://xxx.com") } }
  • 10. public class Twitter { public void getFeeds(TwitterApi api) { api.getFeeds(); } } public class TwitterApi { HttpClient httpClient; public TwitterApi(HttpClient httpClient) { this.httpClient = httpClient; } }
  • 11. What’s the problem now? ● Hard to use ● Manage dependency graph is a mess ● Dagger is the rescue
  • 13. Dagger 2 ● Dependency Injection tool ● Simple Annotation structure ● Readable generated code ● No reflection (fast) ● No runtime error ● Proguard friendly ● Pure Java ● https://github.com/google/dagger ● https://android.jlelse.eu/dagger-2-c00f31decda5
  • 14. Annotation Processing ● Annotate in source code ● Start compile ● Read Annotation and relevant data ● Generate code under build folder ● Compile finish ● https://medium.com/@jintin/annotation-pr ocessing-in-java-3621cb05343a
  • 15. Annotations in Dagger2 ● @Provides ● @Module ● @Component ● @Inject (in Java) ● @Qualifier (@Named) ● @Scope (@Singleton)
  • 17. // Object class class Lemon class Bee class Honey(var bee: Bee) class HoneyLemonade @Inject constructor(var honey: Honey, var lemon: Lemon)
  • 18. @Provides Lemon provideLemon() { return new Lemon(); } @Provides Honey provideHoney(Bee bee) { return new Honey(bee); } @Provides Bee provideBee() { return new Bee(); }
  • 19. @Module public class DrinkModule { @Provides Lemon provideLemon() {...} @Provides Honey provideHoney(Bee bee) {...} @Provides Bee provideBee() {...} }
  • 20. @Component(modules = {DrinkModule.class}) public interface DrinkComponent { HoneyLemonade drink(); void inject(MainActivity activity); }
  • 21. public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DrinkComponent co = DaggerDrinkComponent.create(); HoneyLemonade drink = co.drink(); } }
  • 22. public class MainActivity extends AppCompatActivity { @Inject HoneyLemonade drink; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DrinkComponent co = DaggerDrinkComponent.create(); co.inject(this); } }
  • 23. Recap ● Provides: provide dependency ● Modules: group Provides ● Component: The relation graph ● Inject: Identifier for inject
  • 24. Other feature ● Qualifier: Named... ● Scope: Singleton... ● Subcomponent / includes ● Lazy / Provider...
  • 25. Demo
  • 27. koin ● Service locator by Kotlin DSL ● No code generation ● No reflection ● No compile time overhead ● Pure Kotlin ● https://github.com/InsertKoinIO/koin
  • 28. Service locator The service locator pattern is a design pattern used in software development to encapsulate the processes involved in obtaining a service with a strong abstraction layer.
  • 30. Kotlin DSL ● Function literals with receiver ● Describe data structure ● Like Anko, ktor
  • 31. // HTML DSL val result = html { head { title {+"XML encoding with Kotlin"} } body { h1 {+"XML encoding with Kotlin"} p {+"this format can be used"} a(href = "http://kotlinlang.org") {+"Kotlin"} } }
  • 32. fun html(init: HTML.() -> Unit): HTML { val html = HTML() html.init() return html } fun body(init: Body.() -> Unit) : Body { val body = Body() body.init() return body }
  • 33. koin DSL ● Module - create a Koin Module ● Factory - provide a factory bean definition ● Single - provide a singleton bean definition (also aliased as bean) ● Get - resolve a component dependency
  • 34. // gradle install dependencies { // Koin for Android compile 'org.koin:koin-android:1.0.2' // or Koin for Lifecycle scoping compile 'org.koin:koin-android-scope:1.0.2' // or Koin for Android Architecture ViewModel compile 'org.koin:koin-android-viewmodel:1.0.2' }
  • 35. // Object class class Bee class Honey(var bee: Bee) class Lemon class HoneyLemonade(var honey: Honey, var lemon: Lemon)
  • 36. class MyApplication : Application() { override fun onCreate(){ super.onCreate() // start Koin! startKoin(this, listOf(myModule)) } } val myModule = module { single { Bee() } single { Honey(get()) } single { Lemon() } single { HoneyLemonade(get(), get()) } }
  • 37. // How get() work? reified inline fun <reified T : Any> get( name: String = "", scopeId: String? = null, noinline parameters: ParameterDefinition = ... ): T { val scope: Scope? = scopeId?.let { koinContext.getScope(scopeId) } return koinContext.get(name, scope, parameters) }
  • 38. reified function ● Work with inline ● Can access actual type T ● After compile T will replace with actual type
  • 39. class MyActivity() : AppCompatActivity() { val drink : HoneyLemonade by inject() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val drink : HoneyLemonade = get() } }
  • 40. // How inject(), get() work? inline fun <reified T : Any> ComponentCallbacks.inject( name: String = "", scope: Scope? = null, noinline parameters: ParameterDefinition = ... ) = lazy { get<T>(name, scope, parameters) } inline fun <reified T : Any> ComponentCallbacks.get( name: String = "", scope: Scope? = null, noinline parameters: ParameterDefinition = ... ): T = getKoin().get(name, scope, parameters) // What is ComponentCallbacks btw?
  • 41. Demo
  • 43. Dagger ● Pros: ○ + Pure Java ○ + Stable, flexible, powerful ○ + No Runtime error ○ + Fast in Runtime ● Cons: ○ - Compile overhead ○ - Hard to learn
  • 44. koin ● Pros: ○ + No Annotation processing ○ + Easy to learn/setup ● Cons: ○ - Hard to replace/remove ○ - Test in its env ○ - Error in Runtime
  • 45. “you and only you are responsible for your life choices and decisions” - Robert T. Kiyosaki