Step #3: Depositing a Koin
As was noted earlier, Koin can supply ViewModel
objects via dependency injection to activities and fragments. However, we have to teach it what ViewModel
classes are available for injection.
So, in ToDoApp
, modify the koinModule
property to add in a viewModel
line:
private val koinModule = module {
single { ToDoRepository() }
viewModel { RosterMotor(get()) }
}
single()
is a Koin DSL function that says “make a singleton instance of this object available to those needing it”. viewModel()
is a Koin DSL function that says “use the AndroidX ViewModel
system to make this ViewModel
available to those activities and fragments that need it”. There are a few possible Koin import
statements you could have for viewModel()
— the one that you want is:
import org.koin.androidx.viewmodel.dsl.viewModel
In our case, we are saying that we are willing to supply instances of RosterMotor
to interested activities and fragments. To satisfy the RosterMotor
constructor, we use get()
to retrieve a ToDoRepository
from Koin itself. When it comes time to create an instance of RosterMotor
, Koin will get the ToDoRepository
singleton and supply it to the RosterMotor
constructor.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.