What’s the best way to accomplish manual dependenc...
# android
m
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)
}
m
that’s just doing the same thing but suppressing the warning, isn’t it?
l
Yes. It also prevents you from writing the boilerplate again and again
b
You can use dependency injection to override the viewmodel inside your tests. Have a look into my SampleProject https://github.com/thebino/SampleProject/blob/master/android/app/src/androidTest/java/com/example/home/HomeFragmentTest.kt#L56