Enjoy DI life with Koin - Aaron Chu === ### Dagger2 Dagger2 has too many annotations and it's too complicated to use. ## Koin ### What is Koin? A pragmatic lightweight dependency injection framework for Kotlin developers. **Koin is a DSL, a lightweight container and a pramatic API.** ### Koin Setup(1/2) Define module ```kotlin= val repoModule = module { single { ... } factory { ... } } ``` `single` -> Singleton ### Koin Setup(2/2) `Start Koin` ```kotlin= startKoin { ... } ``` ### Koin Injection ```kotlin= // Lazy injection private val repo: FeatureRepo by inject() // Injects immediately private val repo: FeatureRepo by get() ``` ### Binding an Interface ```kotlin= private val repo: FeatureInterface by inject() ``` ### Naming definitions ### Where are `inject()` and `get()` from? `inject()` and `get()` are extension function of Kolin. ## MVP(Model-View-Presenter) with Koin ```kotlin= val presenterModule = module { // With MainActivity's lifecycle scope(named<MainActivity>()) { scoped<Presenter> { FeaturePresenter() } } } ``` ```kotlin= MainActivity { private val presenter: FeatureContract.Presenter by currentScope.inject { parametersOf(this) } } ``` ### Where is current scope from? ## MVVM(Model-View-ViewModel) with Koin ### Get ViewModel in other FragmentActivity ```kotlin= private val viewModel: FeatureViewModel by viewModel() ``` Get ViewModel in other fragments ```kotlin= private val viewModel: FeatureViewModel by sharedViewModel() ``` ## Inject anywhere ```kotlin= interface KoinComponent { fun getKoin(): Koin = GlobalContext.get().koin } ``` ```kotlin= class ApiClient : KoinComponent { private val apiClient: ApiClient by inject() } ``` Example of ViewController // TODO ### Inject view model declared in viewModel() anywhere? No, because ViewModel is tied to Activity or Fragment Solution: use the instance of `FragmentActivity` or `Fragment` to inject viewModel. ## Unit test ### Check Modules ```kotlin= class MyTest @Test fun `check modules`() { startKoin { modules(viewModelModule) } }.checkModules() ``` * unit test 結束後記得要做stopKoin ### Check Modules with Parameters ### Declare Mocks on the Fly ###### tags: `DevFest2019`