如何将存储库注入ViewModel?

时间:2019-04-13 15:25:31

标签: android dagger-2 android-architecture-components

我正在使用Dagger 2,并且有一个DiComponent定义如下:

@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);
}

这是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);
    }

}

但是,mRepository变量始终为null。

如何使用Dagger 2将存储库注入到ViewModel中?

1 个答案:

答案 0 :(得分:1)

我建议为此设置一个ViewModel工厂。

这是一本好书:

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

进行设置,为存储库类添加@Provides,然后可以注入存储库。