如何使用Dagger2和Java在自定义ViewModel类中注入存储库对象?

时间:2019-07-17 13:23:55

标签: android dependency-injection dagger-2 dagger

我想将MyRepository对象直接注入我的ViewModel类中,但是我总是得到一个NullPointerException。这就是我尝试过的。

这是我的AppModule班:

@Module
public class AppModule {
    @Singleton
    @Provides
    static Retrofit provideRetrofitInstance(){
        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    @Provides
    static MyApi provideMyApi(Retrofit retrofit){
        return retrofit.create(MyApi.class);
    }

    @Provides
    static MyRepository provideMyRepository(MyApi myApi) {
        return new MyRepository(myApi);
    }
}

这是我要注入的课程:

@Singleton
public class MyViewModel extends AndroidViewModel {
    @Inject MyRepository myRepository; //Is not injected!!!
    LiveData<Data> myLiveData;

    MyViewModel(Application application, City city) {
        super(application);
        myLiveData = myRepository.addDataToLiveData(city);
    }

    LiveData<Data> getLiveData() {
        return myLiveData;
    }
}

这是我的存储库类:

public class MyRepository {
    private MyApi myApi;

    public MyRepository(MyApi myApi) {
        this.myApi = myApi;
    }

    LiveData<Data> addDataToLiveData(City city) {
        //Make api call
    }
}

1 个答案:

答案 0 :(得分:0)

使您的存储库构造函数可注入

public class MyRepository {
private MyApi myApi;

@Inject 
public MyRepository(MyApi myApi) {
    this.myApi = myApi;
}

LiveData<Data> addDataToLiveData(City city) {
    //Make api call
} }

并从模块

中删除此存储库提供程序
  @Provides
static MyRepository provideMyRepository(MyApi myApi) {
    return new MyRepository(myApi);
}

应用模块

@Module
public class AppModule {
    @Singleton
    @Provides
    static Retrofit provideRetrofitInstance(){
        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    @Provides
    static MyApi provideMyApi(Retrofit retrofit){
        return retrofit.create(MyApi.class);
    }
}

并从viewModel中删除Singleton批注

public class MyViewModel extends AndroidViewModel {
    @Inject MyRepository myRepository; //Is not injected!!!
    LiveData<Data> myLiveData;

    MyViewModel(Application application, City city) {
        super(application);
        myLiveData = myRepository.addDataToLiveData(city);
    }

    LiveData<Data> getLiveData() {
        return myLiveData;
    }
}