androiddependency-injectiondagger-2daggerdefault-method

Is there a way to inject an object into an interface using Dagger2


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?


Solution

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