Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - by viewModels() with injectable constructor on ViewModel

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?

like image 376
RipNation Avatar asked Dec 03 '19 12:12

RipNation


1 Answers

You need to do several things in order to inject stuff into viewmodel:

  1. Having custom ViewModelFactory which would be part of your graph
  2. Bind your Viewmodel class into the graph
  3. Inject this factory to your Fragment
  4. Use custom factory in the viewModels method by viewModels { theInjectedFactory}

All steps 1-3 are described in many articles or answers on SO, check e.g:

  • Inject property into ViewModel using Dagger 2

PS: as EpicPandaForce mentioned, you shouldn't have your viewmodel marked with @Singleton

like image 174
mlykotom Avatar answered Oct 04 '22 21:10

mlykotom