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

C# Tutorial MSM_Murach chapter-12-slides
C# Tutorial MSM_Murach chapter-12-slidesC# Tutorial MSM_Murach chapter-12-slides
C# Tutorial MSM_Murach chapter-12-slidesSami Mut
 
Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Xavier Hallade
 
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式Shengyou Fan
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytestHector Canto
 
코틀린 멀티플랫폼, 미지와의 조우
코틀린 멀티플랫폼, 미지와의 조우코틀린 멀티플랫폼, 미지와의 조우
코틀린 멀티플랫폼, 미지와의 조우Arawn Park
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkArulalan T
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST APIFabien Vauchelles
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 
Py.test
Py.testPy.test
Py.testsoasme
 
[수정본] 우아한 객체지향
[수정본] 우아한 객체지향[수정본] 우아한 객체지향
[수정본] 우아한 객체지향Young-Ho Cho
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기Arawn Park
 
La programmation par contraintes avec Choco3 (Java)
La programmation par contraintes avec Choco3 (Java)La programmation par contraintes avec Choco3 (Java)
La programmation par contraintes avec Choco3 (Java)Aline Figoureux
 
Criando uma grid para execução de testes paralelo com Appium
Criando uma grid para execução de testes paralelo com AppiumCriando uma grid para execução de testes paralelo com Appium
Criando uma grid para execução de testes paralelo com AppiumElias Nogueira
 
Introduction to react native
Introduction to react nativeIntroduction to react native
Introduction to react nativeDani Akash
 
애플리케이션 아키텍처와 객체지향
애플리케이션 아키텍처와 객체지향 애플리케이션 아키텍처와 객체지향
애플리케이션 아키텍처와 객체지향 Young-Ho Cho
 
React Native - Getting Started
React Native - Getting StartedReact Native - Getting Started
React Native - Getting StartedTracy Lee
 

What's hot (20)

C# Tutorial MSM_Murach chapter-12-slides
C# Tutorial MSM_Murach chapter-12-slidesC# Tutorial MSM_Murach chapter-12-slides
C# Tutorial MSM_Murach chapter-12-slides
 
Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)
 
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 
코틀린 멀티플랫폼, 미지와의 조우
코틀린 멀티플랫폼, 미지와의 조우코틀린 멀티플랫폼, 미지와의 조우
코틀린 멀티플랫폼, 미지와의 조우
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 
Softwaretests: Motivation und Überblick
Softwaretests: Motivation und ÜberblickSoftwaretests: Motivation und Überblick
Softwaretests: Motivation und Überblick
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Py.test
Py.testPy.test
Py.test
 
Android Internals
Android InternalsAndroid Internals
Android Internals
 
[수정본] 우아한 객체지향
[수정본] 우아한 객체지향[수정본] 우아한 객체지향
[수정본] 우아한 객체지향
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
La programmation par contraintes avec Choco3 (Java)
La programmation par contraintes avec Choco3 (Java)La programmation par contraintes avec Choco3 (Java)
La programmation par contraintes avec Choco3 (Java)
 
Criando uma grid para execução de testes paralelo com Appium
Criando uma grid para execução de testes paralelo com AppiumCriando uma grid para execução de testes paralelo com Appium
Criando uma grid para execução de testes paralelo com Appium
 
Introduction to react native
Introduction to react nativeIntroduction to react native
Introduction to react native
 
애플리케이션 아키텍처와 객체지향
애플리케이션 아키텍처와 객체지향 애플리케이션 아키텍처와 객체지향
애플리케이션 아키텍처와 객체지향
 
React Native - Getting Started
React Native - Getting StartedReact Native - Getting Started
React Native - Getting Started
 
Introduction to android testing
Introduction to android testingIntroduction to android testing
Introduction to android testing
 

Similar to KOIN for dependency Injection

Mobile Fest 2018. Кирилл Розов. Insert Koin
Mobile Fest 2018. Кирилл Розов. Insert KoinMobile Fest 2018. Кирилл Розов. Insert Koin
Mobile Fest 2018. Кирилл Розов. Insert KoinMobileFest2018
 
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 ComponentsHassan Abid
 
Real World Asp.Net WebApi Applications
Real World Asp.Net WebApi ApplicationsReal World Asp.Net WebApi Applications
Real World Asp.Net WebApi ApplicationsEffie Arditi
 
CommercialSystemsBahman.ppt
CommercialSystemsBahman.pptCommercialSystemsBahman.ppt
CommercialSystemsBahman.pptKalsoomTahir2
 
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 practiceStefanTomm
 
How to code to code less
How to code to code lessHow to code to code less
How to code to code lessAnton Novikau
 
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.4nobby
 
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 nexusEmily Jiang
 
Titanium appcelerator my first app
Titanium appcelerator my first appTitanium appcelerator my first app
Titanium appcelerator my first appAlessio Ricco
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EEAlexis Hassler
 
2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdfDeoDuaNaoHet
 
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 inGR8Conf
 
Cloud nativemicroservices jax-london2020
Cloud nativemicroservices   jax-london2020Cloud nativemicroservices   jax-london2020
Cloud nativemicroservices jax-london2020Emily Jiang
 
Cloud nativemicroservices jax-london2020
Cloud nativemicroservices   jax-london2020Cloud nativemicroservices   jax-london2020
Cloud nativemicroservices jax-london2020Emily Jiang
 
Grails Plugin Best Practices
Grails Plugin Best PracticesGrails Plugin Best Practices
Grails Plugin Best PracticesBurt Beckwith
 
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 ExtendedToru Wonyoung Choi
 

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

Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKirill Rozov
 
2 years without Java. Kotlin only
2 years without Java. Kotlin only2 years without Java. Kotlin only
2 years without Java. Kotlin onlyKirill Rozov
 
Почему Kotlin?
Почему Kotlin?Почему Kotlin?
Почему Kotlin?Kirill Rozov
 
ConstraintLayout. Fell the Power of constraints
ConstraintLayout. Fell the Power of constraintsConstraintLayout. Fell the Power of constraints
ConstraintLayout. Fell the Power of constraintsKirill Rozov
 
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 platformsKirill Rozov
 
Kotlin - следующий язык после Java
Kotlin - следующий язык после JavaKotlin - следующий язык после Java
Kotlin - следующий язык после JavaKirill Rozov
 
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 3Kirill Rozov
 
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 2Kirill Rozov
 
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 1Kirill Rozov
 
Тестирование на Android с Dagger 2
Тестирование на Android с Dagger 2Тестирование на Android с Dagger 2
Тестирование на Android с Dagger 2Kirill Rozov
 
Что нового в Android O (Grodno HTP)
Что нового в Android O (Grodno HTP)Что нового в Android O (Grodno HTP)
Что нового в Android O (Grodno HTP)Kirill Rozov
 
What's new in Android O
What's new in Android OWhat's new in Android O
What's new in Android OKirill Rozov
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle IntroductionKirill Rozov
 
Kotlin для Android
Kotlin для AndroidKotlin для Android
Kotlin для AndroidKirill Rozov
 
What's new in Android M
What's new in Android MWhat's new in Android M
What's new in Android MKirill 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 Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
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...roncy bisnoi
 
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...ranjana rawat
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
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.pdfankushspencer015
 
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 Conduitsrknatarajan
 
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.pptxupamatechverse
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
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 NashikCall Girls in Nagpur High Profile
 
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)simmis5
 
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 Performancesivaprakash250
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 

Recently uploaded (20)

VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
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...
 
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...
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
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
 
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
 
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
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
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
 
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)
 
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
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 

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