0

Dagger2在App中的实现

网络组件的模块

    @Provides
    @Singleton
    OkHttpClient provideOkHttpClient() {

        return new OkHttpClient.Builder().addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request.Builder builder = chain.request().newBuilder()
                        .addHeader("Accept", "application/json")
                        .addHeader("Client-Id", Constants.CONFIG.APP_NAME)
                        .addHeader("RE-Phone-Number", phoneNumber)
                        .addHeader("RE-Access-Token", access_token);
                Request request = builder.build();
                return chain.proceed(request);
            }
        }).build();
    }

它在应用程序的开头调用一次。我需要在他们获得后更改用户凭据。

@Provides
@Singleton
Retrofit provideRetrofit(GsonConverterFactory gsonConverterFactory,
                         RxJavaCallAdapterFactory rxJavaCallAdapterFactory,
                         OkHttpClient okHttpClient) {
    return new Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(okHttpClient)
            .addConverterFactory(gsonConverterFactory)
            .addCallAdapterFactory(rxJavaCallAdapterFactory)
            .build();
}

Api 组件的模块

@Module
public class ApiModule {

@Provides
@PerFragment
CompanyService provideCompanyService(Retrofit retrofit){
    return retrofit.create(CompanyService.class);
}

}

4

0 回答 0