0

In my activity class, I can inject a ViewModel using:

@Inject
GameViewModel gameViewModel;

And it works fine. The problem is, that I want to use the object in an interface:

public interface SharedData {
    @Inject
    GameViewModel gameViewModel;

    default void createNewUser(User authenticatedUser) {
        gameViewModel.userLiveData.observe(this, user -> {
            Log.d("TAG", user.name);
        });
    }
}

Is this even possible? Because I get:

Variable gameViewModel might not have been initialized

Isn't Dagger supposed to do that?

Pathis Patel
  • 179
  • 1
  • 11
  • I think if you `@Inject` the viewmodel in the activity, then you'll get a new instance every time the activity is recreated, for example, when the phone rotates and a config change happens. This defeats the purpose of the viewmodel which is supposed to survive config changes. What you want to do is inject the viewmodel factory and get the viewmodel using the viewmodelprovider and the injected factory. As for injecting viewmodel in the interface, it sounds like a bad abstraction – denvercoder9 May 02 '20 at 21:24
  • @sonnet Ok, thanks sonnet. – Pathis Patel May 03 '20 at 03:54

1 Answers1

1

You cannot use fields in an interface. To use fields, you should be using a class, or an abstract class.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428