Created
January 21, 2017 08:25
-
-
Save agustarc/d509099edd3cd1231b6da74ab105579f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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