Created
September 7, 2018 06:59
-
-
Save bapspatil/7cd61ecd3318e30e3943ef3341afecd4 to your computer and use it in GitHub Desktop.
Final code snippet for cache-enabled Retrofit
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
val cacheSize = (5 x 1024 x 1024).toLong() | |
val myCache = Cache(context.cacheDir, cacheSize) | |
val okHttpClient = OkHttpClient.Builder() | |
.cache(myCache) | |
.addInterceptor { chain -> | |
var request = chain.request() | |
request = if (hasNetwork(context)!!) | |
request.newBuilder().header("Cache-Control", "public, max-age=" + 5).build() | |
else | |
request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build() | |
chain.proceed(request) | |
} | |
.build() | |
val retrofit = Retrofit.Builder() | |
.baseUrl(BASE_URL) | |
.addConverterFactory(GsonConverterFactory.create()) | |
.client(okHttpClient) | |
.build() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment