1

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?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Héctor
  • 24,444
  • 35
  • 132
  • 243
  • If you aren't using Dagger 2, what dependency injection framework are you using? You don't get injection magically, you have to use some library for it. – Gabe Sechan Nov 29 '17 at 15:04
  • Why? I have built many apps without any DI framework... – Héctor Nov 29 '17 at 15:05
  • Sure, you can do that. But then you won't get anything injected. If you want injection, you need to use something that does it. – Gabe Sechan Nov 29 '17 at 15:06
  • But I can manage my own DI (using constructors or whathever). In this case, Android ViewModel "framework" is preventing me from do it. – Héctor Nov 29 '17 at 15:08
  • Sure, if you want to spend a lot of time reinventing the wheel. But this is a common failing of ALL injection frameworks where you work with a library that constructs objects. The solution is to do the injection after the framework returns the object. Just like you have to manually call inject() in dagger for Activities and Views. Java doesn't provide any better tools for it. Or modify the library itself, but that isn't possible with the Android framework. – Gabe Sechan Nov 29 '17 at 15:10
  • https://stackoverflow.com/a/53956997/7558125 – Pratik Mhatre Dec 28 '18 at 10:37

0 Answers0