Slide 1

Slide 1 text

Dependency injection for Kotlin apps with Koin Arnaud Giuliani @arnogiu

Slide 2

Slide 2 text

! Freelance Software Eng " Mobile First Lead of Koin project Arnaud GIULIANI

Slide 3

Slide 3 text

Why a new dependency injection framework?

Slide 4

Slide 4 text

The CoffeeMaker App ☕ * aka the thermosiphon dagger’s nightmare sample app

Slide 5

Slide 5 text

Pump +pump() Thermosiphon Heater +off() +on() +isHot() ElectricHeater CoffeeMaker +brew()

Slide 6

Slide 6 text

The Heater

Slide 7

Slide 7 text

interface Heater { fun on() fun off() fun isHot() : Boolean }

Slide 8

Slide 8 text

class ElectricHeater : Heater { var heating: Boolean = false override fun on() { println("~ ~ ~ heating ~ ~ ~") heating = true } override fun off() { heating = false } override fun isHot(): Boolean = heating }

Slide 9

Slide 9 text

The Thermosiphon

Slide 10

Slide 10 text

interface Pump { fun pump() }

Slide 11

Slide 11 text

class Thermosiphon(val heater: Heater) : Pump{ override fun pump() { if (heater.isHot()){ println("=> => pumping => =>") } } }

Slide 12

Slide 12 text

The CoffeeMaker

Slide 13

Slide 13 text

class CoffeeMaker(val pump: Pump, val heater: Heater) { fun brew() { heater.on() pump.pump() println(" [_]P coffee! [_]P ") heater.off() } }

Slide 14

Slide 14 text

The CoffeeApp

Slide 15

Slide 15 text

class CoffeeApp { val coffeeMaker: CoffeeMaker fun run() { coffeeMaker.brew() } }

Slide 16

Slide 16 text

Pump +pump() Thermosiphon Heater +off() +on() +isHot() ElectricHeater CoffeeMaker +brew() how to assemble it?

Slide 17

Slide 17 text

class ElectricHeater : Heater class Thermosiphon(val heater: Heater) : Pump class CoffeeMaker(val pump: Pump, val heater: Heater) // bootstrap from an injector // ---- // heater : Heater = ElectricHeater() // pump : Pump = Thermosiphon(heater) // coffeeMaker = CoffeeMaker(heater,pump) val coffeeMaker = Injector.get()

Slide 18

Slide 18 text

{ Thermosiphon(get()) } { ElectricHeater() } Provide Provide

Slide 19

Slide 19 text

Koin

Slide 20

Slide 20 text

- Intuitive DSL to describe it - Lightweight container to run it - Simple API to use it - Pure Kotlin!

Slide 21

Slide 21 text

repositories { jcenter() } dependencies { // Koin for Kotlin implementation ‘org.koin:koin-core:$version’ } Gradle Setup

Slide 22

Slide 22 text

// declare definitions here module { }

Slide 23

Slide 23 text

module { // definition single | factory { instance creation expression } }

Slide 24

Slide 24 text

class ElectricHeater : Heater class Thermosiphon(val heater: Heater) : Pump class CoffeeMaker(val pump: Pump, val heater: Heater)

Slide 25

Slide 25 text

class ElectricHeater : Heater class Thermosiphon(val heater: Heater) : Pump class CoffeeMaker(val pump: Pump, val heater: Heater) val coffeeMakerModule = module { single { CoffeeMaker(get(),get()) } single{ Thermosiphon(get()) } single { ElectricHeater() } } * also multi modules

Slide 26

Slide 26 text

class ElectricHeater : Heater class Thermosiphon(val heater: Heater) : Pump class CoffeeMaker(val pump: Pump, val heater: Heater) val coffeeMaker = module { single { CoffeeMaker(get(),get()) } } val coffeeParts = module { single{ Thermosiphon(get()) } single { ElectricHeater() } } * also multi modules

Slide 27

Slide 27 text

Koin Component a class that can use the Koin container

Slide 28

Slide 28 text

✅ open access to Kotlin extensions: inject(), get() identify a class linked to the Koin API KoinComponent is an interface marker bootstrap & help integrate with runtime (Android…)

Slide 29

Slide 29 text

class CoffeeApp : KoinComponent { val coffeeMaker: CoffeeMaker by inject() fun run() { coffeeMaker.brew() } }

Slide 30

Slide 30 text

The CoffeeApp

Slide 31

Slide 31 text

startKoin to start the Koin container

Slide 32

Slide 32 text

class CoffeeApp : KoinComponent { val coffeeMaker: CoffeeMaker by inject() fun run() { coffeeMaker.brew() } } fun main(vararg args: String) { }

Slide 33

Slide 33 text

fun run() { coffeeMaker.brew() } } fun main(vararg args: String) { startKoin { } }

Slide 34

Slide 34 text

fun run() { coffeeMaker.brew() } } fun main(vararg args: String) { startKoin { modules(coffeeMakerModule) } }

Slide 35

Slide 35 text

fun run() { coffeeMaker.brew() } } fun main(vararg args: String) { startKoin { modules(coffeeMakerModule) } CoffeeApp().run() }

Slide 36

Slide 36 text

~ ~ ~ heating ~ ~ ~ => => pumping => => [_]P coffee! [_]P

Slide 37

Slide 37 text

No content

Slide 38

Slide 38 text

Can’t create Android components directly

Slide 39

Slide 39 text

Activity, Fragment, Service … are extended as KoinComponent! out of the box! ✅ Koin extensions for Android

Slide 40

Slide 40 text

repositories { jcenter() } dependencies { // Koin for Android implementation ‘org.koin:koin-android:$version’ } Gradle Setup

Slide 41

Slide 41 text

class MyApplication : Application() { override fun onCreate() { super.onCreate() // Add Android Koin Logger startKoin { androidLogger() modules(coffeeMakerModule) } } }

Slide 42

Slide 42 text

class MyApplication : Application() { override fun onCreate() { super.onCreate() // Reference Android context in Koin startKoin { androidLogger() androidContext(this@MyApplication) modules(coffeeMakerModule) } } }

Slide 43

Slide 43 text

class MyActivity : AppCompatActivity() { val coffeeMaker: CoffeeMaker by inject() }

Slide 44

Slide 44 text

Get the Android context?

Slide 45

Slide 45 text

class MyApplication : Application() { override fun onCreate() { super.onCreate() // Reference Android context in Koin startKoin { androidLogger() androidContext(this@MyApplication) modules(coffeeMakerModule) } } }

Slide 46

Slide 46 text

class MyComponent(val context : Context) val myModule = module { single { MyComponent(androidContext()) } }

Slide 47

Slide 47 text

class MyComponent(val context : Context) val myModule = module { single { MyComponent(get()) } }

Slide 48

Slide 48 text

Dealing with transient components? ie. presenters …

Slide 49

Slide 49 text

class MyPresenter(val coffeeMaker : CoffeeMaker) val myModule = module { // will create MyPresenter on each call factory { MyPresenter(get()) } }

Slide 50

Slide 50 text

class MyPresenter(val coffeeMaker : CoffeeMaker) val myModule = module { // will create MyPresenter on each call factory { MyPresenter(get()) } } class MyActivity : AppCompatActivity() { // new instance on each call val presenter: MyPresenter by inject() }

Slide 51

Slide 51 text

Ready for Android Architecture Components

Slide 52

Slide 52 text

repositories { jcenter() } dependencies { // Koin for Android + ViewModel features implementation ‘org.koin:koin-android-viewmodel:$version’ implementation ‘org.koin:koin-androidx-viewmodel:$version’ } Gradle Setup

Slide 53

Slide 53 text

✅ Koin extensions for Android ViewModel

Slide 54

Slide 54 text

class MyViewModel(val coffeeMaker : CoffeeMaker) : ViewModel() val coffeeMakerModule = module { viewModel { MyViewModel(get()) } }

Slide 55

Slide 55 text

//... viewModel { MyViewModel(get()) } } class MyActivity : AppCompatActivity() { // inject ViewModel val myViewModel: MyViewModel by viewModel()

Slide 56

Slide 56 text

//... viewModel { MyViewModel(get()) } } class MyFragment : Fragment() { // inject ViewModel val myViewModel: MyViewModel by viewModel()

Slide 57

Slide 57 text

//... viewModel { MyViewModel(get()) } } class MyFragment : Fragment() { // inject ViewModel from parent activity val myViewModel: MyViewModel by sharedViewModel()

Slide 58

Slide 58 text

Injecting Bundle State in ViewModel

Slide 59

Slide 59 text

repositories { jcenter() } dependencies { // Koin for Android Fragments feature implementation ‘org.koin:koin-androidx-viewmodel:$version’ } Gradle Setup 2.1.0-alpha-4

Slide 60

Slide 60 text

// Inject your state class StateViewModel(val state: SavedStateHandle) : ViewModel() // use injection parameter to get state viewModel { (handle: SavedStateHandle, id: String) -> StateViewModel(handle, id, get()) } // Provide initial state as parameter class MVVMActivity : AppCompatActivity() { val mySavedVM: StateViewModel by viewModel { parametersOf(Bundle(), "vm1") } }

Slide 61

Slide 61 text

// Inject your state class StateViewModel( val handle: SavedStateHandle, val id: String, val service: SimpleService) : ViewModel() // use injection parameter to get state viewModel { (handle: SavedStateHandle) -> StateViewModel(handle, id, get()) } // Provide initial state as parameter class MVVMActivity : AppCompatActivity() { val mySavedVM: StateViewModel by viewModel { parametersOf(Bundle(), "vm1") } }

Slide 62

Slide 62 text

// Inject your state class StateViewModel( val handle: SavedStateHandle, val id: String, val service: SimpleService) : ViewModel() // use injection parameter to get state viewModel { (handle: SavedStateHandle, id: String) -> StateViewModel(handle, id, get()) } // Provide initial state as parameter class MVVMActivity : AppCompatActivity() { val mySavedVM: StateViewModel by viewModel { parametersOf(Bundle()) } }

Slide 63

Slide 63 text

Inject your Fragments

Slide 64

Slide 64 text

repositories { jcenter() } dependencies { // Koin for Android Fragments feature implementation ‘org.koin:koin-androidx-fragment:$version’ } Gradle Setup 2.1.0-alpha-4

Slide 65

Slide 65 text

// Use constructor injection :) class MyFragment(val session: Session) : Fragment() // Declare your fragment val module = module { single { Session() } fragment { MyFragment(get()) } } // Setup in Activity class MyMActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { // setup factory setupKoinFragmentFactory() super.onCreate(savedInstanceState)

Slide 66

Slide 66 text

// Use constructor injection :) class MyFragment(val session: Session) : Fragment() // Declare your fragment val module = module { single { Session() } fragment { MyFragment(get()) } } // Setup in Activity class MyMActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { // setup factory setupKoinFragmentFactory() super.onCreate(savedInstanceState)

Slide 67

Slide 67 text

// Setup in Activity class MyMActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { // setup factory setupKoinFragmentFactory() super.onCreate(savedInstanceState) // Call your Fragment supportFragmentManager.beginTransaction() .replace(R.id.fragment, MyFragment::class.java, null, null) .commit() } }

Slide 68

Slide 68 text

// Setup in Activity class MyMActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { // setup factory setupKoinFragmentFactory() super.onCreate(savedInstanceState) // Call your Fragment supportFragmentManager.beginTransaction() .replace(R.id.fragment, MyFragment::class.java, null, null) .commit() } }

Slide 69

Slide 69 text

Ktor Web Applications

Slide 70

Slide 70 text

repositories { jcenter() } dependencies { // Koin for Ktor compile ‘org.koin:koin-ktor:$version’ // Koin SLF4J Logger compile ‘org.koin:koin-logger-slf4j:$version’ } Gradle Setup

Slide 71

Slide 71 text

fun main(args: Array) { // Start Ktor embeddedServer(Netty, commandLineEnvironment(args)).start() } fun Application.main() { install(DefaultHeaders) install(CallLogging) // Routing section routing { get("/hello") { call.respondText(...) } } }

Slide 72

Slide 72 text

fun main(args: Array) { // Start Ktor embeddedServer(Netty, commandLineEnvironment(args)).start() } fun Application.main() { install(DefaultHeaders) install(CallLogging) // Routing section routing { get("/coffee") { call.respondText(...) } } }

Slide 73

Slide 73 text

fun Application.main() { install(DefaultHeaders) install(CallLogging) install(Koin) { slf4jLogger() modules(coffeeMakerModule) } // Routing section routing { get(“/coffee") { call.respondText(...) } } }

Slide 74

Slide 74 text

fun Application.main() { install(DefaultHeaders) install(CallLogging) install(Koin) { slf4jLogger() modules(coffeeMakerModule) } val coffeeMaker by inject() // Routing section routing { get("/coffee") { call.respondText(...) } } }

Slide 75

Slide 75 text

fun Application.main() { install(DefaultHeaders) install(CallLogging) install(Koin) { slf4jLogger() modules(coffeeMakerModule) } val coffeeMaker by inject() // Routing section routing { get("/coffee") { call.respondText(coffeeMaker.printBrew()) } } }

Slide 76

Slide 76 text

Application, Route, Routing … are extended as KoinComponent! out of the box! ✅ Koin extensions for Ktor

Slide 77

Slide 77 text

class ElectricHeater : Heater class Thermosiphon(val heater: Heater) : Pump class CoffeeMaker(val pump: Pump, val heater: Heater) val coffeeMakerModule = module(createdAtStart = true) { single() singleBy() singleBy() }

Slide 78

Slide 78 text

Testing easily with Koin ✅

Slide 79

Slide 79 text

repositories { jcenter() } dependencies { // Koin for Tests testImplementation ‘org.koin:koin-test:$version’ } Gradle Setup In rewrite!

Slide 80

Slide 80 text

Checking your modules ✔

Slide 81

Slide 81 text

class ModuleTest { @Test fun `check all definitions from coffeeMakerModule`() { startKoin { modules(coffeeMakerModule) }.checkModules() } }

Slide 82

Slide 82 text

✅ Koin extensions with JUnit & Mockito

Slide 83

Slide 83 text

class CoffeeMakerTest : KoinTest { val coffeeMaker: CoffeeMaker by inject() val heater: Heater by inject() @Test fun testHeaterIsTurnedOnAndThenOff() { startKoin { modules(coffeeMakerModule) } } }

Slide 84

Slide 84 text

class CoffeeMakerTest : KoinTest { val coffeeMaker: CoffeeMaker by inject() val heater: Heater by inject() @Test fun testHeaterIsTurnedOnAndThenOff() { startKoin { modules(coffeeMakerModule) } declareMock() } }

Slide 85

Slide 85 text

class CoffeeMakerTest : KoinTest { val coffeeMaker: CoffeeMaker by inject() val heater: Heater by inject() @Test fun testHeaterIsTurnedOnAndThenOff() { startKoin { modules(coffeeMakerModule) } declareMock() given(heater.isHot()).will { true } coffeeMaker.brew() verify(heater, times(1)).on() verify(heater, times(1)).off() } }

Slide 86

Slide 86 text

More about Koin✨

Slide 87

Slide 87 text

- Container DSL - Qualifiers (string/type) - Global vs isolated context - Scope API - Android, Scopes & lifecycle - Injection Parameters - AndroidX - Koin for Java - Koin for Ktor

Slide 88

Slide 88 text

Koin 2.0

Slide 89

Slide 89 text

Since first 1.0 version…

Slide 90

Slide 90 text

Simple DSL module, single, factory, get

Slide 91

Slide 91 text

Pragmatic API ✌ KoinComponent, get, inject

Slide 92

Slide 92 text

No content

Slide 93

Slide 93 text

No content

Slide 94

Slide 94 text

* startup & Kotlin overhead ** split modules startup if needed

Slide 95

Slide 95 text

Benchmarks https://github.com/InsertKoinIO/thermosiphon_dagger2koin https://github.com/Sloy/android-dependency-injection-performance https://github.com/arnaudgiuliani/android-dependency-injection-performance

Slide 96

Slide 96 text

http://bit.ly/ready4koin

Slide 97

Slide 97 text

- Container DSL - Qualifiers (string/type) - Global vs isolated context - Scope API - Android, Scopes & lifecycle - Injection Parameters - AndroidX - Koin for Java - Koin for Ktor

Slide 98

Slide 98 text

- Container DSL - Qualifiers (string/type) - Global vs isolated context - Scope API - Android, Scopes & lifecycle - Injection Parameters - AndroidX - Koin for Java - Koin for Ktor

Slide 99

Slide 99 text

Dependency injection & Service Locator?

Slide 100

Slide 100 text

Dependency injection & Service Locator

Slide 101

Slide 101 text

class Thermosiphon(val heater : Heater) : Pump class ElectricHeater() : Heater module { single{ Thermosiphon(get()) } single { ElectricHeater() } } Dependency Injection - Constructor injection configured via Koin DSL - Your classes are not dependant to Koin API - Instances are called by Koin Container - Functional DSL Configuration: parameters, context, scopes…

Slide 102

Slide 102 text

class CoffeeApp : KoinComponent { val coffeeMaker by inject() } Service Locator - Use the Koin API to retrieve a dependency - “Host” class not created by Koin

Slide 103

Slide 103 text

Is service locator bad?

Slide 104

Slide 104 text

class CoffeeApp : KoinComponent { // Lazily ask for instance val coffeeMaker : CoffeeMaker by inject() } Service Locator class CoffeeApp { lateinit var coffeeMaker : CoffeeMaker init { // ask injection of setters DI.inject(this) } } Setter Injection

Slide 105

Slide 105 text

0

Slide 106

Slide 106 text

80% of your Koin usage will be configuration 20% will be platform extensions Limit your dependency to Koin as much as possible

Slide 107

Slide 107 text

The choice between Service Locator and Dependency Injection is less important than the principle of separating service configuration from the use of services within an application. Martin Fowler

Slide 108

Slide 108 text

Functional Dependency Injection

Slide 109

Slide 109 text

Function and Container Context

Slide 110

Slide 110 text

val coffeeMakerModule = module { single { CoffeeMaker(get(),get()) } single{ Thermosiphon(get()) } single { ElectricHeater() } } typealias Definition = Scope.(DefinitionParameters) -> T

Slide 111

Slide 111 text

Definition Parameters DSL Extension Scope

Slide 112

Slide 112 text

Function to inject parameters

Slide 113

Slide 113 text

class MyPresenter(val id : String) val myModule = module { factory { (id : String) -> MyPresenter(id)} }

Slide 114

Slide 114 text

val myModule = module { factory { (id : String) -> MyPresenter(id)} } class MyActivity : AppCompatActivity(){ val presenter : MyPresenter by inject { parametersOf("42")} }

Slide 115

Slide 115 text

class MyViewModel(val id : String) val myModule = module { viewModel { (id : String) -> MyViewModel(id)} }

Slide 116

Slide 116 text

val myModule = module { viewModel { (id : String) -> MyViewModel(id)} } class MyActivity : AppCompatActivity(){ val presenter : MyViewModel by viewModel { parametersOf("42")} }

Slide 117

Slide 117 text

✨ Simpler declaration with Reflection ✨

Slide 118

Slide 118 text

A.k.a “Get rid of get() get() get() get() get()”

Slide 119

Slide 119 text

Functional Dependency Injection 0

Slide 120

Slide 120 text

repositories { jcenter() } dependencies { // Koin for Android implementation ‘org.koin:koin-core-ext:$version’ } Gradle Setup

Slide 121

Slide 121 text

class ElectricHeater : Heater class Thermosiphon(val heater: Heater) : Pump class CoffeeMaker(val pump: Pump, val heater: Heater) val coffeeMakerModule = module { single { CoffeeMaker(get(),get()) } single{ Thermosiphon(get()) } single { ElectricHeater() } }

Slide 122

Slide 122 text

class ElectricHeater : Heater class Thermosiphon(val heater: Heater) : Pump class CoffeeMaker(val pump: Pump, val heater: Heater) val coffeeMakerModule = module { single() singleBy() singleBy() }

Slide 123

Slide 123 text

Available out of the box for pure JVM platforms (Ktor, TornadoFx…)

Slide 124

Slide 124 text

repositories { jcenter() } dependencies { // Koin for Android implementation ‘org.koin:koin-android-ext:$version’ implementation ‘org.koin:koin-androidx-ext:$version’ } Gradle Setup

Slide 125

Slide 125 text

class MyViewModel(val coffeeMaker : CoffeeMaker) : ViewModel() val coffeeMakerModule = module { viewModel() }

Slide 126

Slide 126 text

Add following pro guard rules https://insert-koin.io/docs/2.0/quick-references/experimental-features/#proguard-rule

Slide 127

Slide 127 text

Check performances Pure functional DSL declaration is 4x - 10x faster * definition execution time ** depending on devices (< Android 6)

Slide 128

Slide 128 text

Let’s migrate to Koin, what else?

Slide 129

Slide 129 text

Refactoring is not always sustainable

Slide 130

Slide 130 text

« Hard to switch from our current DI » Top #1 issue

Slide 131

Slide 131 text

No content

Slide 132

Slide 132 text

What if you could… run it easily in a module ✨

Slide 133

Slide 133 text

startKoin { modules(…) } loadKoinModules(…) Definition Definition Definition unloadKoinModules(…)

Slide 134

Slide 134 text

Making dynamic modules with Koin - Load dynamic modules/definitions - Change implementation on the fly - Easy to compose step by step

Slide 135

Slide 135 text

Onboarding Wallet Profile Transactions Profile v2 Payments Card Management Onboarding Onboarding v2

Slide 136

Slide 136 text

Dynamic Modules Architecture - Registry / Plugin architecture - Feature <> Libraries isolation (modules) - Navigation, Feature Flagging, A/B testing …

Slide 137

Slide 137 text

What’s next?

Slide 138

Slide 138 text

No content

Slide 139

Slide 139 text

Tips & Best pratices

Slide 140

Slide 140 text

Try the getting started projects * look at code samples

Slide 141

Slide 141 text

start.insert-koin.io

Slide 142

Slide 142 text

doc.insert-koin.io

Slide 143

Slide 143 text

Add it step by step to your project * start with small components

Slide 144

Slide 144 text

Check your modules ✅

Slide 145

Slide 145 text

Keep it simple

Slide 146

Slide 146 text

and …

Slide 147

Slide 147 text

StackOverflow, Github & Slack for any question

Slide 148

Slide 148 text

No content

Slide 149

Slide 149 text

@insertkoin_io koin-developers

Slide 150

Slide 150 text

Thank you! All the community…

Slide 151

Slide 151 text

stable_version = “2.0.1" unstable_version = “2.1.0-alpha-4” repositories { jcenter() } dependencies { // Core features compile "org.koin:koin-core:$version" // Ktor compile "org.koin:koin-ktor:$version" compile "org.koin:koin-logger-slf4j:$version" // Android implementation "org.koin:koin-android:$version"

Slide 152

Slide 152 text

dependencies { // Core features compile "org.koin:koin-core:$version" // Ktor compile "org.koin:koin-ktor:$version" compile "org.koin:koin-logger-slf4j:$version" // Android implementation "org.koin:koin-android:$version" // Android + ViewModel implementation "org.koin:koin-android-viewmodel:$version" // JUnit & Mockito testImplementation "org.koin:koin-test:$version" }

Slide 153

Slide 153 text

dependencies { // Core features compile "org.koin:koin-core:$version" // Ktor compile "org.koin:koin-ktor:$version" compile "org.koin:koin-logger-slf4j:$version" // Android implementation "org.koin:koin-android:$version" // Android + ViewModel implementation "org.koin:koin-android-viewmodel:$version" // JUnit & Mockito testImplementation "org.koin:koin-test:$version" }

Slide 154

Slide 154 text

dependencies { // Core features compile "org.koin:koin-core:$version" // Ktor compile "org.koin:koin-ktor:$version" compile "org.koin:koin-logger-slf4j:$version" // Android implementation “org.koin:koin-android:$version” // Android + ViewModel implementation "org.koin:koin-android-viewmodel:$version" // JUnit & Mockito testImplementation "org.koin:koin-test:$version" }

Slide 155

Slide 155 text

dependencies { // Core features compile "org.koin:koin-core:$version" // Ktor compile "org.koin:koin-ktor:$version" compile "org.koin:koin-logger-slf4j:$version" // Android implementation "org.koin:koin-android:$version" // Android + ViewModel implementation "org.koin:koin-android-viewmodel:$version" // JUnit & Mockito testImplementation "org.koin:koin-test:$version" }

Slide 156

Slide 156 text

insert-koin.io

Slide 157

Slide 157 text

Arnaud Giuliani - @arnogiu Thank you!