If you want to provide viewmodel with constructor as a dependency in your Fragment, there is a different method for it,
Lets suppose you have a viewmodel class as belows,
class SampleViewmModel(dataManager:DataManager):ViewModel(){
//some logic
}
Then you will need to create a factory class to support above viewmodel like below,
class SampleFactory @Inject constructor(var dataManager:DataManager): ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(SampleViewModel::class.java)) {
return SampleViewModel(dataManager) as T
}
throw IllegalStateException()
}
}
Now in your module class, you can inject above classes as below, (Note-Datamanager class is injectible)
//Provide Factory
@Provides
fun provideFactory(dataManager:DataManager): SampleFactory {
return SampleFactory(dataManager)
}
//Provide actual viewmodel
@Provides
fun provideViewModel(sampleFactory: SampleFactory): SampleViewModel {
return ViewModelProviders.of(fragment, sampleFactory)[SampleViewModel::class]
}
No in your Fragment, you can inject your viewmodel just like any other dependency,
@Injetct
lateinit viewModel:SampleViewModel
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…