Skip to content

Instantly share code, notes, and snippets.

@agustarc
Created January 21, 2017 08:25
Show Gist options
  • Save agustarc/d509099edd3cd1231b6da74ab105579f to your computer and use it in GitHub Desktop.
Save agustarc/d509099edd3cd1231b6da74ab105579f to your computer and use it in GitHub Desktop.
@Module
public class SampleModule {
private static final int CONNECT_TIMEOUT = 15;
private static final int WRITE_TIMEOUT = 15;
private static final int READ_TIMEOUT = 15;
private static final String baseUrl; // your base url;
@Provides
@Singleton
Cache provideOkHttpCache(Application application) {
final int cacheSize = 10 * 1024 * 1024; // 10MB
return new Cache(application.getCacheDir(), cacheSize);
}
@Provides
@Singleton
Gson provideGson() {
return new GsonBuilder()
.registerTypeAdapterFactory(AutoValueGsonFactory.create())
.create();
}
@Provides
@Singleton
OkHttpClient provideOkHttpClient(Cache cache, Interceptor interceptor) {
return new OkHttpClient.Builder()
.cache(cache)
.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
.addInterceptor(interceptor)
.build();
}
@Provides
@Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
return new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(baseUrl)
.client(okHttpClient)
.build();
}
@Provides
@Singleton
Interceptor provideInterceptor(AccountPreferences prefs) {
return chain -> {
if (StringUtil.isNotEmpty(prefs.getToken())) {
final String bearer = "BEARER " + prefs.getToken();
final Request.Builder builder = chain.request().newBuilder()
.header("Authorization", bearer)
.header("Accept", "application/json");
return chain.proceed(builder.build());
} else {
return chain.proceed(chain.request());
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment