Was wondering how someone would deal with this.
I have a fragment that has a respective view model. That view model has an injected repo in its constructor. However when using "by viewModels()" to create the view model instance in my fragment I'm getting an error.
Example:
@Singleton
class MyViewModel @Inject constructor(val someRepo: SomeRepo) : ViewModel() { ... }
class MyFragment : BaseFragment(), Injectable {
val myViewModel: MyViewModel by viewModels()
...
}
Error: java.lang.RuntimeException: Cannot create an instance of class com.example.MVVM.ViewModel.MyViewModel
Has anyone got this to work without creating their own viewModelFactory?
You need to do several things in order to inject stuff into viewmodel:
by viewModels { theInjectedFactory}
All steps 1-3 are described in many articles or answers on SO, check e.g:
PS: as EpicPandaForce mentioned, you shouldn't have your viewmodel marked with @Singleton
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With