I've seen many tutorials for MVVM. Most of them say that you need to define your ViewModel class like this:
class MainViewModel: ViewModel() {
...
}
But recently I stumbled upon Dagger tutorial project from Google. There is a different ViewModel class definition:
class MainViewModel(private val userDataRepository: UserDataRepository) {
...
}
So I wonder, what is the difference between these two approaches?
CodePudding user response:
That's not a relevant comparison. That CodeLab uses a non-ViewModel ViewModel class to simplify their explanation of how DI works. Notice it doesn't subclass ViewModel. Also, the project starts without the dependency injection and has you add it in later, so the starting project isn't intended to be a good example of how to design something.
Either way, if you have a repository, you need some way to get a reference to the repository in your ViewModel. If it is through the constructor, you would have to get a reference to the repository in the associated ViewModelFactory that you build for this class. If you use Dagger, you'll probably let Dagger generate this factory for you and inject the reference.
If your ViewModel doesn't use a repository, then you won't have any reason to have one in your constructor, with or without dependency injection. Many basic MVVM tutorials are going to start with the most basic possible example, a ViewModel with no arguments needed. That doesn't imply that a ViewModel should never have dependencies.