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

Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 formsEyal Vardi
 
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive FormsAngular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive FormsDigamber Singh
 
Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Roman Elizarov
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to HooksSoluto
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeRamon Ribeiro Rabello
 
Analysing in depth work manager
Analysing in depth work managerAnalysing in depth work manager
Analysing in depth work managerbhatnagar.gaurav83
 
DDD (Debugger Driven Development)
DDD (Debugger Driven Development)DDD (Debugger Driven Development)
DDD (Debugger Driven Development)Carlos Granados
 
Webpack Introduction
Webpack IntroductionWebpack Introduction
Webpack IntroductionAnjali Chawla
 
Utilizing kotlin flows in an android application
Utilizing kotlin flows in an android applicationUtilizing kotlin flows in an android application
Utilizing kotlin flows in an android applicationSeven Peaks Speaks
 
Collections in Java
Collections in JavaCollections in Java
Collections in JavaKhasim Cise
 
Build web apps with react js
Build web apps with react jsBuild web apps with react js
Build web apps with react jsdhanushkacnd
 
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Edureka!
 

What's hot (20)

Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive FormsAngular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive Forms
 
React Hooks
React HooksReact Hooks
React Hooks
 
Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack Compose
 
Analysing in depth work manager
Analysing in depth work managerAnalysing in depth work manager
Analysing in depth work manager
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
React lecture
React lectureReact lecture
React lecture
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
DDD (Debugger Driven Development)
DDD (Debugger Driven Development)DDD (Debugger Driven Development)
DDD (Debugger Driven Development)
 
React js
React jsReact js
React js
 
Webpack Introduction
Webpack IntroductionWebpack Introduction
Webpack Introduction
 
Utilizing kotlin flows in an android application
Utilizing kotlin flows in an android applicationUtilizing kotlin flows in an android application
Utilizing kotlin flows in an android application
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Webpack slides
Webpack slidesWebpack slides
Webpack slides
 
Build web apps with react js
Build web apps with react jsBuild web apps with react js
Build web apps with react js
 
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
 

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

Presentation on Slab, Beam, Column, and Foundation/Footing
Presentation on Slab,  Beam, Column, and Foundation/FootingPresentation on Slab,  Beam, Column, and Foundation/Footing
Presentation on Slab, Beam, Column, and Foundation/FootingEr. Suman Jyoti
 
Circuit Breakers for Engineering Students
Circuit Breakers for Engineering StudentsCircuit Breakers for Engineering Students
Circuit Breakers for Engineering Studentskannan348865
 
Call for Papers - Journal of Electrical Systems (JES), E-ISSN: 1112-5209, ind...
Call for Papers - Journal of Electrical Systems (JES), E-ISSN: 1112-5209, ind...Call for Papers - Journal of Electrical Systems (JES), E-ISSN: 1112-5209, ind...
Call for Papers - Journal of Electrical Systems (JES), E-ISSN: 1112-5209, ind...Christo Ananth
 
Databricks Generative AI Fundamentals .pdf
Databricks Generative AI Fundamentals  .pdfDatabricks Generative AI Fundamentals  .pdf
Databricks Generative AI Fundamentals .pdfVinayVadlagattu
 
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024EMMANUELLEFRANCEHELI
 
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdfInvolute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdfJNTUA
 
Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...IJECEIAES
 
Path loss model, OKUMURA Model, Hata Model
Path loss model, OKUMURA Model, Hata ModelPath loss model, OKUMURA Model, Hata Model
Path loss model, OKUMURA Model, Hata ModelDrAjayKumarYadav4
 
Geometric constructions Engineering Drawing.pdf
Geometric constructions Engineering Drawing.pdfGeometric constructions Engineering Drawing.pdf
Geometric constructions Engineering Drawing.pdfJNTUA
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Ramkumar k
 
一比一原版(Griffith毕业证书)格里菲斯大学毕业证成绩单学位证书
一比一原版(Griffith毕业证书)格里菲斯大学毕业证成绩单学位证书一比一原版(Griffith毕业证书)格里菲斯大学毕业证成绩单学位证书
一比一原版(Griffith毕业证书)格里菲斯大学毕业证成绩单学位证书c3384a92eb32
 
Autodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptxAutodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptxMustafa Ahmed
 
Augmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxAugmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxMustafa Ahmed
 
Filters for Electromagnetic Compatibility Applications
Filters for Electromagnetic Compatibility ApplicationsFilters for Electromagnetic Compatibility Applications
Filters for Electromagnetic Compatibility ApplicationsMathias Magdowski
 
Databricks Generative AI FoundationCertified.pdf
Databricks Generative AI FoundationCertified.pdfDatabricks Generative AI FoundationCertified.pdf
Databricks Generative AI FoundationCertified.pdfVinayVadlagattu
 
DBMS-Report on Student management system.pptx
DBMS-Report on Student management system.pptxDBMS-Report on Student management system.pptx
DBMS-Report on Student management system.pptxrajjais1221
 
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...ronahami
 
SLIDESHARE PPT-DECISION MAKING METHODS.pptx
SLIDESHARE PPT-DECISION MAKING METHODS.pptxSLIDESHARE PPT-DECISION MAKING METHODS.pptx
SLIDESHARE PPT-DECISION MAKING METHODS.pptxCHAIRMAN M
 
Diploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdfDiploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdfJNTUA
 

Recently uploaded (20)

Presentation on Slab, Beam, Column, and Foundation/Footing
Presentation on Slab,  Beam, Column, and Foundation/FootingPresentation on Slab,  Beam, Column, and Foundation/Footing
Presentation on Slab, Beam, Column, and Foundation/Footing
 
Circuit Breakers for Engineering Students
Circuit Breakers for Engineering StudentsCircuit Breakers for Engineering Students
Circuit Breakers for Engineering Students
 
Call for Papers - Journal of Electrical Systems (JES), E-ISSN: 1112-5209, ind...
Call for Papers - Journal of Electrical Systems (JES), E-ISSN: 1112-5209, ind...Call for Papers - Journal of Electrical Systems (JES), E-ISSN: 1112-5209, ind...
Call for Papers - Journal of Electrical Systems (JES), E-ISSN: 1112-5209, ind...
 
Databricks Generative AI Fundamentals .pdf
Databricks Generative AI Fundamentals  .pdfDatabricks Generative AI Fundamentals  .pdf
Databricks Generative AI Fundamentals .pdf
 
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
 
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdfInvolute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
 
Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...
 
Path loss model, OKUMURA Model, Hata Model
Path loss model, OKUMURA Model, Hata ModelPath loss model, OKUMURA Model, Hata Model
Path loss model, OKUMURA Model, Hata Model
 
Geometric constructions Engineering Drawing.pdf
Geometric constructions Engineering Drawing.pdfGeometric constructions Engineering Drawing.pdf
Geometric constructions Engineering Drawing.pdf
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)
 
一比一原版(Griffith毕业证书)格里菲斯大学毕业证成绩单学位证书
一比一原版(Griffith毕业证书)格里菲斯大学毕业证成绩单学位证书一比一原版(Griffith毕业证书)格里菲斯大学毕业证成绩单学位证书
一比一原版(Griffith毕业证书)格里菲斯大学毕业证成绩单学位证书
 
Autodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptxAutodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptx
 
Augmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxAugmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptx
 
Filters for Electromagnetic Compatibility Applications
Filters for Electromagnetic Compatibility ApplicationsFilters for Electromagnetic Compatibility Applications
Filters for Electromagnetic Compatibility Applications
 
Databricks Generative AI FoundationCertified.pdf
Databricks Generative AI FoundationCertified.pdfDatabricks Generative AI FoundationCertified.pdf
Databricks Generative AI FoundationCertified.pdf
 
Signal Processing and Linear System Analysis
Signal Processing and Linear System AnalysisSignal Processing and Linear System Analysis
Signal Processing and Linear System Analysis
 
DBMS-Report on Student management system.pptx
DBMS-Report on Student management system.pptxDBMS-Report on Student management system.pptx
DBMS-Report on Student management system.pptx
 
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
 
SLIDESHARE PPT-DECISION MAKING METHODS.pptx
SLIDESHARE PPT-DECISION MAKING METHODS.pptxSLIDESHARE PPT-DECISION MAKING METHODS.pptx
SLIDESHARE PPT-DECISION MAKING METHODS.pptx
 
Diploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdfDiploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdf
 

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