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

What's hot (20)

Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
Jetpack compose
Jetpack composeJetpack compose
Jetpack compose
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack Compose
 
Introduction to NodeJS
Introduction to NodeJSIntroduction to NodeJS
Introduction to NodeJS
 
Angular 9
Angular 9 Angular 9
Angular 9
 
Angular modules in depth
Angular modules in depthAngular modules in depth
Angular modules in depth
 
Kotlin Jetpack Tutorial
Kotlin Jetpack TutorialKotlin Jetpack Tutorial
Kotlin Jetpack Tutorial
 
Advanced angular
Advanced angularAdvanced angular
Advanced angular
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Kotlin Basics & Introduction to Jetpack Compose.pptx
Kotlin Basics & Introduction to Jetpack Compose.pptxKotlin Basics & Introduction to Jetpack Compose.pptx
Kotlin Basics & Introduction to Jetpack Compose.pptx
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
 
Angular 5 presentation for beginners
Angular 5 presentation for beginnersAngular 5 presentation for beginners
Angular 5 presentation for beginners
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2
 
Jetpack Compose - Android’s modern toolkit for building native UI
Jetpack Compose - Android’s modern toolkit for building native UIJetpack Compose - Android’s modern toolkit for building native UI
Jetpack Compose - Android’s modern toolkit for building native UI
 
React Native
React NativeReact Native
React Native
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Data Persistence in Android with Room Library
Data Persistence in Android with Room LibraryData Persistence in Android with Room Library
Data Persistence in Android with Room Library
 
The Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.jsThe Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.js
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
 

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

VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
Tonystark477637
 

Recently uploaded (20)

Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
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...
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 

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