Skip to content

Instantly share code, notes, and snippets.

@AndrejJurkin
Created June 9, 2017 10:08
Show Gist options
  • Save AndrejJurkin/eb839c4ef83bb43d091b72779795650f to your computer and use it in GitHub Desktop.
Save AndrejJurkin/eb839c4ef83bb43d091b72779795650f to your computer and use it in GitHub Desktop.
Dagger module that provides a basic Retrofit - Gson - OkHttp - RxJava setup
@Module
public final class ApiModule {
private static final int OK_HTTP_CACHE_SIZE = 10 * 1024 * 1024;
private static final String GSON_DATE_FORMAT = "yyyy-MM-dd";
private String baseUrl;
private String apiKey;
public ApiModule(String baseUrl, String apiKey) {
this.baseUrl = baseUrl;
this.apiKey = apiKey;
}
@Provides
@Singleton
Cache providesOkHttpCache(App app) {
return new Cache(app.getCacheDir(), OK_HTTP_CACHE_SIZE);
}
@Provides
@Singleton
Gson providesGson() {
Gson gson = new GsonBuilder()
.setDateFormat(GSON_DATE_FORMAT)
.create();
return gson;
}
@Provides
@Singleton
Interceptor providesApiKeyInterceptor() {
final Interceptor apiKeyInterceptor = chain -> {
HttpUrl url = chain.request().url()
.newBuilder()
.addQueryParameter("api_key", apiKey)
.build();
Request request = chain.request().newBuilder().url(url).build();
return chain.proceed(request);
};
return apiKeyInterceptor;
}
@Provides
@Singleton
HttpLoggingInterceptor providesHttpLoggingInterceptor() {
final HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
if (BuildConfig.DEBUG) {
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
} else {
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
}
return httpLoggingInterceptor;
}
@Provides
@Singleton
OkHttpClient providesOkHttpClient(Cache cache, Interceptor apiKeyInterceptor,
HttpLoggingInterceptor loggingInterceptor) {
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(apiKeyInterceptor)
.addInterceptor(loggingInterceptor)
.cache(cache)
.build();
return client;
}
@Provides
@Singleton
Retrofit providesRetrofit(Gson gson, OkHttpClient client) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory
.createWithScheduler(Schedulers.newThread()))
.client(client)
.build();
return retrofit;
}
@Provides
@Singleton
UserService providesMovieService(Retrofit retrofit) {
return retrofit.create(User.class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment