So, I have been reading about Android ViewModel
class and app architecture guide and I see that a view model is obtained with something like this:
viewModel = ViewModelProviders.of(this).get(UserProfileViewModel.class);
You don't instantiate directly the class, but use the ViewModelProviders
class.
So far, so good. Then, the guide shows how to "connect" the UserProfileViewModel
with a repository UserRepository
:
public class UserProfileViewModel extends ViewModel {
private UserRepository userRepo;
@Inject // UserRepository parameter is provided by Dagger 2
public UserProfileViewModel(UserRepository userRepo) {
this.userRepo = userRepo;
}
//more stuff
}
As comment above says, UserRepository
is injected by Dagger (annotation @Inject
in the constructor).
What if we are not using Dagger 2? How can be a dependency injected in the view model class?