SlideShare a Scribd company logo
1 of 36
Кирилл Розов
Android Developer
Dependency
Injection
Inversion of Control (IoC) is a design principle in
which custom-written portions of a computer
program receive the flow of control from a
generic framework
wikipedia.org/wiki/Inversion_of_control
Inversion of Control
CLIENT
CLIENT
CLIENT
DEPENDENCY 1
DEPENDENCY 2
DEPENDENCY 3
DEPENDENCY 4
Inversion of Control
DEPENDENCY 1
DEPENDENCY 2
DEPENDENCY 3
DEPENDENCY 4
IoC CONTAINER
CLIENT
CLIENT
CLIENT
Inversion of Control
DEPENDENCY 1
DEPENDENCY 2
DEPENDENCY 3
DEPENDENCY 4
IoC CONTAINER
CLIENT
CLIENT
CLIENT
Popular DI
• Guice

• Spring DI

• Square Dagger

• Google Dagger 2

• Java EE CDI

• PicoContainer

• Kodein

• Koin
insert-Koin.io
Koin Supports
Android App
Spark Web AppStandalone App
Arch Components
Sample usage
val sampleModule = applicationContext {
bean { ComponentA() }
}
class Application : KoinComponent {
val component by inject<ComponentA>() // Inject (lazy)
val component = get<ComponentA>() // Get (eager)
}
fun main(vararg args: String) {
startKoin(listOf(sampleModule))
}
Init Koin
class SampleApplication : Application() {
override fun onCreate() {
startKoin(this, listOf(sampleModule))
}
}
fun main(vararg args: String) {
startKoin(listOf(sampleModule))
}
fun main(vararg args: String) {
start(listOf(sampleModule)) { … }
}
Provide dependencies
applicationContext {
bean { ComponentA() } // singletone
factory { ComponentB() } // factory
}
Provide dependencies
applicationContext {
bean { ComponentB() }
bean { ComponentA(get<ComponentB>()) }
}
Named dependencies
applicationContext {
bean(“debug”) { ComponentB() }
bean(“prod”) { ComponentB() }
bean { ComponentA(get(“debug”)) }
}
class Application : KoinComponent {
val component by inject<ComponentB>(“prod”)
}
Type binding
applicationContext {
bean { ComponentImpl() }
bean { ComponentImpl() as Component }
bean { ComponentImpl() } bind Component::class
}
Properties
applicationContext {
bean { RestService(getProperty(“url”)) }
}
class RestService(url: String)
applicationContext {
bean { RestService(getProperty(“url”, “http://localhost”)) }
}
val key1Property: String by property(“key1”)
Additional properties
// Properties has type Map<String, Any>
startKoin(properties =
mapOf(“key1" to "value", “key2” to 1)
)
Properties Sources
• koin.properties in JAR resources

• koin.properties in assets

• Environment properties
Environment variables
startKoin(useEnvironmentProperties = true)
// Get user name from properties
val key1Property: String by property(“USER”)
Parameters
applicationContext {
factory { params: ParametersProvider ->
NewsDetailsPresenter(params[NEWS_ID])
}
}
val presenter: NewsDetailsPresenter
by inject { mapOf(NEWS_ID to "sample") }
interface ParametersProvider {
operator fun <T> get(key: String): T
fun <T> getOrNull(key: String): T?
}
Contexts
applicationContext {
context("main") {
bean { ComponentA() }
bean { ComponentB() }
}
}
class MainActivity : Activity() {
override fun onStop() {
releaseContext("main")
}
}
Context isolation
applicationContext { // Root
context("A") {
context("B") {
bean { ComponentA() }
}
}
context("C") {
bean { ComponentA() }
}
}
Android Arch Components
Default Way
class ListFragment : Fragment() {
val listViewModel =
ViewModelProviders.of(this).get(ListViewModel::class.java)
}
Koin Way
applicationContext {
viewModel { ListViewModel() }
}
class ListFragment : Fragment() {
val listViewModel by viewModel<ListViewModel>()
val listViewModel = getViewModel<ListViewModel>()
}
ViewModel with arguments
class DetailViewModel(id: String) : ViewModel()
class DetailFactory(val id: String) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass == DetailViewModel::class.java) {
return DetailViewModel(id) as T
}
error("Can't create ViewModel for class='$modelClass'")
}
}
class ListFragment : Fragment() {
val listViewModel =
ViewModelProviders.of(this, DetailFactory(id))
.get(TeacherViewModel::class.java)
}
Koin Way
applicationContext {
viewModel { params -> DetailViewModel(params["id"]) }
}
class ListFragment : Fragment() {
val listViewModel
by viewModel<ListViewModel> { mapOf("id" to "sample") }
val listViewModel =
getViewModel<ListViewModel> { mapOf("id" to "sample") }
}
Logging
applicationContext {
factory { Presenter(get()) }
bean { Repository(get()) }
bean { DebugDataSource() } bind DateSource::class
}
get<Presenter>()
get<Presenter>()
(KOIN) :: Resolve [Presenter] ~ Factory[class=Presenter]
(KOIN) :: Resolve [Repository] ~ Bean[class=Repository]
(KOIN) :: Resolve [Datasource] ~ Bean[class=DebugDatasource, binds~(Datasource)]
(KOIN) :: (*) Created
(KOIN) :: (*) Created
(KOIN) :: (*) Created
(KOIN) :: Resolve [Repository] ~ Factory[class=Repository]
(KOIN) :: Resolve [DebugDatasource] ~ Bean[class=DebugDatasource, binds~(Datasource)]
(KOIN) :: (*) Created
class Presenter(repository: Repository)
class Repository(dateSource: DateSource)
interface DateSource
class DebugDataSource() : DateSource
Crash Logs
Cyclic dependencies
org.koin.error.BeanInstanceCreationException: Can't create bean Bean[class=ComponentA] due to error :
BeanInstanceCreationException: Can't create bean Bean[class=ComponentB] due to error :
BeanInstanceCreationException: Can't create bean Bean[class=ComponentA] due to error :
DependencyResolutionException: Cyclic dependency detected while resolving class ComponentA
applicationContext {
bean { ComponentA(get()) }
bean { ComponentB(get()) }
}
class ComponentA(component: ComponentB)
class ComponentB(component: ComponentA)
get<ComponentA>()
Missing dependency
applicationContext {
bean { ComponentA(get()) }
bean { ComponentB(get()) }
}
class ComponentA(component: ComponentB)
class ComponentB(component: ComponentA)
get<ComponentC>()
org.koin.error.DependencyResolutionException:
No definition found for ComponentC - Check your definitions and contexts visibility
Graph
Validation
Graph validation
class ComponentA(component: ComponentB)
class ComponentB(component: ComponentC)
class ComponentC()
val sampleModule = applicationContext {
bean { ComponentA(get()) }
factory { ComponentB(get()) }
}
class DryRunTest : KoinTest {
@Test
fun dryRunTest() {
startKoin(listOf(sampleModule))
dryRun()
}
}
Koin vs Dagger 2
Koin Dagger2
Simpler usage Yes -
How work No reflection or code generation Codegeneration
Support
Kotlin, Java, Android, Arch Components,
Spark, Koin
Java, Android
Transitive dependency injection - Yes
Dependencies declaration In modules, DSL
Annotated functions in module

Annotations on class
Library Size 83 Kb (v 0.9.1) 38 Kb (v 2.15)
Generic type resolve - Yes
Named dependencies Yes Yes
Scopes Yes Yes
Lazy injection Yes Yes
Graph validation Dry Run Compile time
Logs Yes -
Additional Features Environment property injection,
parametrised injection
Multibindings, Reusable Scope
Thanks insert-Koin.io
krl.rozov@gmail.com
krlrozov
Кирилл Розов
Android Developer

More Related Content

What's hot

[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...
[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...
[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...
Shengyou Fan
 

What's hot (20)

Spring Boot
Spring BootSpring Boot
Spring Boot
 
Selenium- A Software Testing Tool
Selenium- A Software Testing ToolSelenium- A Software Testing Tool
Selenium- A Software Testing Tool
 
Try Jetpack Compose
Try Jetpack ComposeTry Jetpack Compose
Try Jetpack Compose
 
Asp.Net Core MVC , Razor page , Entity Framework Core
Asp.Net Core MVC , Razor page , Entity Framework CoreAsp.Net Core MVC , Razor page , Entity Framework Core
Asp.Net Core MVC , Razor page , Entity Framework Core
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Android MVVM
Android MVVMAndroid MVVM
Android MVVM
 
Laravel Design Patterns
Laravel Design PatternsLaravel Design Patterns
Laravel Design Patterns
 
MVVM with SwiftUI and Combine
MVVM with SwiftUI and CombineMVVM with SwiftUI and Combine
MVVM with SwiftUI and Combine
 
Understanding .Net Standards, .Net Core & .Net Framework
Understanding .Net Standards, .Net Core & .Net FrameworkUnderstanding .Net Standards, .Net Core & .Net Framework
Understanding .Net Standards, .Net Core & .Net Framework
 
Spring core module
Spring core moduleSpring core module
Spring core module
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...
[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...
[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
[JCConf 2022] Compose for Desktop - 開發桌面軟體的新選擇
[JCConf 2022] Compose for Desktop - 開發桌面軟體的新選擇[JCConf 2022] Compose for Desktop - 開發桌面軟體的新選擇
[JCConf 2022] Compose for Desktop - 開發桌面軟體的新選擇
 
Test automation using selenium
Test automation using seleniumTest automation using selenium
Test automation using selenium
 
Selenium Grid
Selenium GridSelenium Grid
Selenium Grid
 

Similar to KOIN for dependency Injection

CommercialSystemsBahman.ppt
CommercialSystemsBahman.pptCommercialSystemsBahman.ppt
CommercialSystemsBahman.ppt
KalsoomTahir2
 
What's New In Apache Lenya 1.4
What's New In Apache Lenya 1.4What's New In Apache Lenya 1.4
What's New In Apache Lenya 1.4
nobby
 
GR8Conf 2011: Grails, how to plug in
GR8Conf 2011: Grails, how to plug inGR8Conf 2011: Grails, how to plug in
GR8Conf 2011: Grails, how to plug in
GR8Conf
 

Similar to KOIN for dependency Injection (20)

Mobile Fest 2018. Кирилл Розов. Insert Koin
Mobile Fest 2018. Кирилл Розов. Insert KoinMobile Fest 2018. Кирилл Розов. Insert Koin
Mobile Fest 2018. Кирилл Розов. Insert Koin
 
Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture Components
 
Real World Asp.Net WebApi Applications
Real World Asp.Net WebApi ApplicationsReal World Asp.Net WebApi Applications
Real World Asp.Net WebApi Applications
 
CommercialSystemsBahman.ppt
CommercialSystemsBahman.pptCommercialSystemsBahman.ppt
CommercialSystemsBahman.ppt
 
From Java to Kotlin - The first month in practice
From Java to Kotlin - The first month in practiceFrom Java to Kotlin - The first month in practice
From Java to Kotlin - The first month in practice
 
How to code to code less
How to code to code lessHow to code to code less
How to code to code less
 
What's New In Apache Lenya 1.4
What's New In Apache Lenya 1.4What's New In Apache Lenya 1.4
What's New In Apache Lenya 1.4
 
MicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexus
MicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexusMicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexus
MicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexus
 
Titanium appcelerator my first app
Titanium appcelerator my first appTitanium appcelerator my first app
Titanium appcelerator my first app
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Bean Intro
Bean IntroBean Intro
Bean Intro
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
 
2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf
 
GR8Conf 2011: Grails, how to plug in
GR8Conf 2011: Grails, how to plug inGR8Conf 2011: Grails, how to plug in
GR8Conf 2011: Grails, how to plug in
 
Cloud nativemicroservices jax-london2020
Cloud nativemicroservices   jax-london2020Cloud nativemicroservices   jax-london2020
Cloud nativemicroservices jax-london2020
 
Cloud nativemicroservices jax-london2020
Cloud nativemicroservices   jax-london2020Cloud nativemicroservices   jax-london2020
Cloud nativemicroservices jax-london2020
 
Grails Plugin Best Practices
Grails Plugin Best PracticesGrails Plugin Best Practices
Grails Plugin Best Practices
 
Ejb examples
Ejb examplesEjb examples
Ejb examples
 
Dependency injection in iOS
Dependency injection in iOSDependency injection in iOS
Dependency injection in iOS
 
Jetpack, with new features in 2021 GDG Georgetown IO Extended
Jetpack, with new features in 2021 GDG Georgetown IO ExtendedJetpack, with new features in 2021 GDG Georgetown IO Extended
Jetpack, with new features in 2021 GDG Georgetown IO Extended
 

More from Kirill Rozov

More from Kirill Rozov (20)

Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is coming
 
2 years without Java. Kotlin only
2 years without Java. Kotlin only2 years without Java. Kotlin only
2 years without Java. Kotlin only
 
Почему Kotlin?
Почему Kotlin?Почему Kotlin?
Почему Kotlin?
 
Optimize APK size
Optimize APK sizeOptimize APK size
Optimize APK size
 
ConstraintLayout. Fell the Power of constraints
ConstraintLayout. Fell the Power of constraintsConstraintLayout. Fell the Power of constraints
ConstraintLayout. Fell the Power of constraints
 
Kotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platformsKotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platforms
 
Kotlin - следующий язык после Java
Kotlin - следующий язык после JavaKotlin - следующий язык после Java
Kotlin - следующий язык после Java
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
 
Why Kotlin - Apalon Kotlin Sprint Part 1
Why Kotlin - Apalon Kotlin Sprint Part 1Why Kotlin - Apalon Kotlin Sprint Part 1
Why Kotlin - Apalon Kotlin Sprint Part 1
 
Тестирование на Android с Dagger 2
Тестирование на Android с Dagger 2Тестирование на Android с Dagger 2
Тестирование на Android с Dagger 2
 
Что нового в Android O (Grodno HTP)
Что нового в Android O (Grodno HTP)Что нового в Android O (Grodno HTP)
Что нового в Android O (Grodno HTP)
 
What's new in Android O
What's new in Android OWhat's new in Android O
What's new in Android O
 
Android service
Android serviceAndroid service
Android service
 
Effective Java
Effective JavaEffective Java
Effective Java
 
Dagger 2
Dagger 2Dagger 2
Dagger 2
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
REST
RESTREST
REST
 
Kotlin для Android
Kotlin для AndroidKotlin для Android
Kotlin для Android
 
What's new in Android M
What's new in Android MWhat's new in Android M
What's new in Android M
 

Recently uploaded

Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 
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
Cara Menggugurkan Kandungan 087776558899
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
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...
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
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
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 

KOIN for dependency Injection

  • 3. Inversion of Control (IoC) is a design principle in which custom-written portions of a computer program receive the flow of control from a generic framework wikipedia.org/wiki/Inversion_of_control
  • 4. Inversion of Control CLIENT CLIENT CLIENT DEPENDENCY 1 DEPENDENCY 2 DEPENDENCY 3 DEPENDENCY 4
  • 5. Inversion of Control DEPENDENCY 1 DEPENDENCY 2 DEPENDENCY 3 DEPENDENCY 4 IoC CONTAINER CLIENT CLIENT CLIENT
  • 6. Inversion of Control DEPENDENCY 1 DEPENDENCY 2 DEPENDENCY 3 DEPENDENCY 4 IoC CONTAINER CLIENT CLIENT CLIENT
  • 7. Popular DI • Guice • Spring DI • Square Dagger • Google Dagger 2 • Java EE CDI • PicoContainer • Kodein • Koin
  • 9. Koin Supports Android App Spark Web AppStandalone App Arch Components
  • 10. Sample usage val sampleModule = applicationContext { bean { ComponentA() } } class Application : KoinComponent { val component by inject<ComponentA>() // Inject (lazy) val component = get<ComponentA>() // Get (eager) } fun main(vararg args: String) { startKoin(listOf(sampleModule)) }
  • 11. Init Koin class SampleApplication : Application() { override fun onCreate() { startKoin(this, listOf(sampleModule)) } } fun main(vararg args: String) { startKoin(listOf(sampleModule)) } fun main(vararg args: String) { start(listOf(sampleModule)) { … } }
  • 12. Provide dependencies applicationContext { bean { ComponentA() } // singletone factory { ComponentB() } // factory }
  • 13. Provide dependencies applicationContext { bean { ComponentB() } bean { ComponentA(get<ComponentB>()) } }
  • 14. Named dependencies applicationContext { bean(“debug”) { ComponentB() } bean(“prod”) { ComponentB() } bean { ComponentA(get(“debug”)) } } class Application : KoinComponent { val component by inject<ComponentB>(“prod”) }
  • 15. Type binding applicationContext { bean { ComponentImpl() } bean { ComponentImpl() as Component } bean { ComponentImpl() } bind Component::class }
  • 16. Properties applicationContext { bean { RestService(getProperty(“url”)) } } class RestService(url: String) applicationContext { bean { RestService(getProperty(“url”, “http://localhost”)) } } val key1Property: String by property(“key1”)
  • 17. Additional properties // Properties has type Map<String, Any> startKoin(properties = mapOf(“key1" to "value", “key2” to 1) )
  • 18. Properties Sources • koin.properties in JAR resources • koin.properties in assets • Environment properties
  • 19. Environment variables startKoin(useEnvironmentProperties = true) // Get user name from properties val key1Property: String by property(“USER”)
  • 20. Parameters applicationContext { factory { params: ParametersProvider -> NewsDetailsPresenter(params[NEWS_ID]) } } val presenter: NewsDetailsPresenter by inject { mapOf(NEWS_ID to "sample") } interface ParametersProvider { operator fun <T> get(key: String): T fun <T> getOrNull(key: String): T? }
  • 21. Contexts applicationContext { context("main") { bean { ComponentA() } bean { ComponentB() } } } class MainActivity : Activity() { override fun onStop() { releaseContext("main") } }
  • 22. Context isolation applicationContext { // Root context("A") { context("B") { bean { ComponentA() } } } context("C") { bean { ComponentA() } } }
  • 24. Default Way class ListFragment : Fragment() { val listViewModel = ViewModelProviders.of(this).get(ListViewModel::class.java) }
  • 25. Koin Way applicationContext { viewModel { ListViewModel() } } class ListFragment : Fragment() { val listViewModel by viewModel<ListViewModel>() val listViewModel = getViewModel<ListViewModel>() }
  • 26. ViewModel with arguments class DetailViewModel(id: String) : ViewModel() class DetailFactory(val id: String) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass == DetailViewModel::class.java) { return DetailViewModel(id) as T } error("Can't create ViewModel for class='$modelClass'") } } class ListFragment : Fragment() { val listViewModel = ViewModelProviders.of(this, DetailFactory(id)) .get(TeacherViewModel::class.java) }
  • 27. Koin Way applicationContext { viewModel { params -> DetailViewModel(params["id"]) } } class ListFragment : Fragment() { val listViewModel by viewModel<ListViewModel> { mapOf("id" to "sample") } val listViewModel = getViewModel<ListViewModel> { mapOf("id" to "sample") } }
  • 29. applicationContext { factory { Presenter(get()) } bean { Repository(get()) } bean { DebugDataSource() } bind DateSource::class } get<Presenter>() get<Presenter>() (KOIN) :: Resolve [Presenter] ~ Factory[class=Presenter] (KOIN) :: Resolve [Repository] ~ Bean[class=Repository] (KOIN) :: Resolve [Datasource] ~ Bean[class=DebugDatasource, binds~(Datasource)] (KOIN) :: (*) Created (KOIN) :: (*) Created (KOIN) :: (*) Created (KOIN) :: Resolve [Repository] ~ Factory[class=Repository] (KOIN) :: Resolve [DebugDatasource] ~ Bean[class=DebugDatasource, binds~(Datasource)] (KOIN) :: (*) Created class Presenter(repository: Repository) class Repository(dateSource: DateSource) interface DateSource class DebugDataSource() : DateSource
  • 31. Cyclic dependencies org.koin.error.BeanInstanceCreationException: Can't create bean Bean[class=ComponentA] due to error : BeanInstanceCreationException: Can't create bean Bean[class=ComponentB] due to error : BeanInstanceCreationException: Can't create bean Bean[class=ComponentA] due to error : DependencyResolutionException: Cyclic dependency detected while resolving class ComponentA applicationContext { bean { ComponentA(get()) } bean { ComponentB(get()) } } class ComponentA(component: ComponentB) class ComponentB(component: ComponentA) get<ComponentA>()
  • 32. Missing dependency applicationContext { bean { ComponentA(get()) } bean { ComponentB(get()) } } class ComponentA(component: ComponentB) class ComponentB(component: ComponentA) get<ComponentC>() org.koin.error.DependencyResolutionException: No definition found for ComponentC - Check your definitions and contexts visibility
  • 34. Graph validation class ComponentA(component: ComponentB) class ComponentB(component: ComponentC) class ComponentC() val sampleModule = applicationContext { bean { ComponentA(get()) } factory { ComponentB(get()) } } class DryRunTest : KoinTest { @Test fun dryRunTest() { startKoin(listOf(sampleModule)) dryRun() } }
  • 35. Koin vs Dagger 2 Koin Dagger2 Simpler usage Yes - How work No reflection or code generation Codegeneration Support Kotlin, Java, Android, Arch Components, Spark, Koin Java, Android Transitive dependency injection - Yes Dependencies declaration In modules, DSL Annotated functions in module Annotations on class Library Size 83 Kb (v 0.9.1) 38 Kb (v 2.15) Generic type resolve - Yes Named dependencies Yes Yes Scopes Yes Yes Lazy injection Yes Yes Graph validation Dry Run Compile time Logs Yes - Additional Features Environment property injection, parametrised injection Multibindings, Reusable Scope