重新创建Dagger 2改装实例

时间:2018-11-29 04:34:35

标签: android retrofit2 dagger-2

大家好,

我已经在项目中实现了Dagger 2,但是遇到了问题。

我需要能够根据用户选择的国家/地区来更改服务器,这意味着不同的基本URL。

有没有一种方法可以更改Retrofit对象实例上的基本URL?

这是我的代码:

@Singleton
@Provides
MyApiService providesApiService(Retrofit aRetrofit) {
    return aRetrofit.create(MyApiService.class);
}

@Singleton
@Provides
Retrofit provideNetwork(OkHttpClient aOkHttpClient, MyInterceptor aMyInterceptor) {
    return new Retrofit.Builder()
            .baseUrl(aMyInterceptor.getBaseUrl()) //this is where I get the base URL
            .addConverterFactory(GsonConverterFactory.create())
            .callFactory(aOkHttpClient)
            .build();
}

@Singleton
@Provides
OkHttpClient providesOkHttpClient(MyInterceptor aMyInterceptor) {
    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    if (BuildConfig.DEBUG) {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient.addInterceptor(interceptor);
    }
    httpClient.connectTimeout(1, TimeUnit.MINUTES);
    httpClient.addInterceptor(aMyInterceptor);
    return httpClient.build();
}

0 个答案:

没有答案