What’s the best way to accomplish manual dependency injection into viewmodels? The following leads to
Unchecked cast: MyViewModel to T
, which leads me to believe there may be a better way
Copy code
class MyViewModel(private val myDependency: MyDependency) : ViewModel() {}
class MyViewModelFactory(private val myDependency: MyDependency) : ViewModelProvider.NewInstanceFactory() {
override fun <T: ViewModel?> create(modelClass: Class<T>): T {
return MyViewModel(myDependency) as T
}
}
// In activity
private val myViewModel: MyViewModel by lazy {
val myDependency = MyDependency()
ViewModelproviders.of(this, MyViewmodelFactory(myDependency))
.get(MyViewModel::class.java)
}