0

I am using Dagger 2 and I have a DiComponent defined as follows:

@Singleton
@Component(modules = {
        AndroidSupportInjectionModule.class,
        ApplicationModule.class,
        PreferenceModule.class,
        RetrofitModule.class,
        RoomModule.class,
})
public interface DiComponent  {

    void inject(SplashScreen activity);
    void inject(Home activity);

    void inject(FYViewModel viewModel);
    void inject(CFViewModel viewModel);
}

This is the FYViewModel.class:

public class FYViewModel extends AndroidViewModel {
    private static final String TAG = FYViewModel.class.getSimpleName();

    @Inject
    public FYRepository mRepository;

    private LiveData<List<Post>> mPostList;

    public FYViewModel(Application application) {
        super(application);
        Log.d(TAG, "FYViewModel: " + mRepository);
//        mPostList = mRepository.getAllPosts();
    }

    public LiveData<List<Post>> getAllPosts() {
        return mPostList;
    }

    public void fetchNextData(int page) {
        mRepository.fetchNextPosts(page);
    }

}

However, the mRepository variable is always null.

How can I use Dagger 2 to inject Repositroy into my ViewModels?

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
code
  • 2,115
  • 1
  • 22
  • 46

1 Answers1

3

I would recommend setting up a ViewModel factory for this.

Here is a good read:

https://proandroiddev.com/viewmodel-with-dagger2-architecture-components-2e06f06c9455

Set that up, add an @Provides for the repository class, then you can inject your repository.

AzraelPwnz
  • 506
  • 2
  • 12
  • 1
    I ended up doing this in Java using this answer: https://stackoverflow.com/a/49087002/2231031 – code Apr 13 '19 at 17:31