code
code

Reputation: 2163

How to inject Repository into ViewModel?

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?

Upvotes: 0

Views: 5412

Answers (1)

AzraelPwnz
AzraelPwnz

Reputation: 506

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.

Upvotes: 3

Related Questions