首页 > 解决方案 > 如何将 Retrofit 对象直接注入到存储库类中?

问题描述

我想将一个Retrofit对象直接注入我的MyRepository班级,但我总是得到一个NullPointerException. 这是我尝试过的。

这是我的AppModule课:

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

这是我的视图模型类:

public class MyViewModel extends AndroidViewModel {
    LiveData<Data> myLiveData;

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

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

这是我要注入 Retofit 的存储库类:

public class MyRepository {
    private String myTex;
    @Inject
    private Retrofit retrofit;

    public MyRepository(String myText) {
        this.myText = myText;
    }

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

编辑:

这就是我ViewModel在我的活动类中实例化我的方式:

MyRepository repository = new MyRepository("MyText");
Application application = activity.getApplication();
MyViewModelFactory factory = new MyViewModelFactory(application, repository);
MyViewModel viewModel = ViewModelProviders.of(this, factory).get(MyViewModel.class);

标签: androiddependency-injectiondagger-2dagger

解决方案


使您的存储库可注入是最简单的解决方案,它还允许您将它注入到使用它的位置,在您ViewModel的 s 或Interactors 中:

@Singleton
public class MyRepository {

    private Retrofit retrofit;

    @Inject
    public MyRepository(Retrofit retrofit) {
        this.retrofit = retrofit;
    }

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

编辑:您可以通过 Dagger 提供文本并将其注入您的构造函数中,就像这样

@Inject
public MyRepository(String myText, Retrofit retrofit)

请注意,您需要使用@Namedor@Qualifier作为您的字符串。

或者,您可以注入您的存储库调用inject(this),语法取决于您如何设置 Dagger

somehowGetDaggerComponent().inject(this)

我强烈建议您使用第一种解决方案。


推荐阅读