RipNation
RipNation

Reputation: 83

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?

Upvotes: 7

Views: 5458

Answers (1)

mlykotom
mlykotom

Reputation: 5155

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:

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

Upvotes: 7

Related Questions