Skip to content

Instantly share code, notes, and snippets.

@bapspatil
Created September 7, 2018 06:59
Show Gist options
  • Save bapspatil/7cd61ecd3318e30e3943ef3341afecd4 to your computer and use it in GitHub Desktop.
Save bapspatil/7cd61ecd3318e30e3943ef3341afecd4 to your computer and use it in GitHub Desktop.
Final code snippet for cache-enabled Retrofit
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