What’s the best way to accomplish manual dependenc...
# android
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))
that’s just doing the same thing but suppressing the warning, isn’t it?
Yes. It also prevents you from writing the boilerplate again and again
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