Search code examples
androidkotlinkodein

how to make many ViewModelFactory in kodein with kotlin


i use kodein principle in mvvm to set my ViewModelFactory with repositories

class AddSpendApplication: Application(), KodeinAware {

override val kodein: Kodein = Kodein.lazy {
    import(androidXModule(this@AddSpendApplication))
    bind() from singleton { PersonalAccountingDateBase(instance()) }
    bind() from singleton { AddSpendRepository(instance()) }
    bind() from provider { AddSpendViewModelFactory(instance()) }
}}

so when i have many ViewModel in my app , i should make ViewModelFactory for every ViewModel i have then get each repository instance to the ViewModelFactory in kodein scope . with many ViewModelFactory i have how to make them in kodein

i think it's impossible to make another class for each ViewModelFactory because the Application should be write in one place , so how kodein will be write


Solution

  • simply can be defined another repository and viewmodel factory in the same class that inherit from application ,and for each injection process you can get any view model factory instance you want

    class AddSpendApplication: Application(), KodeinAware {
    override val kodein: Kodein = Kodein.lazy {
    import(androidXModule(this@AddSpendApplication))
    bind() from singleton { PersonalAccountingDateBase(instance()) }
    
    bind() from singleton { AddSpendRepository(instance()) }
    bind() from provider { AddSpendViewModelFactory(instance()) }
    
    bind() from singleton { anotherRepository(instance()) }
    bind() from provider { anotherViewModelFactory(instance()) }
    
    .....
    }}