Inject ViewModel using Dagger 2 + Kotlin + ViewModel

后端 未结 6 1380
-上瘾入骨i
-上瘾入骨i 2021-02-07 07:07
class SlideshowViewModel : ViewModel() {

@Inject lateinit var mediaItemRepository : MediaItemRepository

fun init() {
    What goes here?
}

So I\'m tr

6条回答
  •  无人共我
    2021-02-07 07:43

    No. You create a component where you are declaring (using) your viewModel. It is normally an activity/fragment. The viewModel has dependencies (mediaitemrepository), so you need a factory. Something like this:

        class MainViewModelFactory (
                val repository: IExerciseRepository): ViewModelProvider.Factory {
    
            @Suppress("UNCHECKED_CAST")
            override fun  create(p0: Class?): T {
                return MainViewModel(repository) as T
            }
        }
    

    Then the dagger part (activity module)

        @Provides
        @ActivityScope
        fun providesViewModelFactory(
                exerciseRepos: IExerciseRepository
        ) = MainViewModelFactory(exerciseRepos)
    
        @Provides
        @ActivityScope
        fun provideViewModel(
                viewModelFactory: MainViewModelFactory
        ): MainViewModel {
            return ViewModelProviders
                    .of(act, viewModelFactory)
                    .get(MainViewModel::class.java)
        }
    

提交回复
热议问题