Skip to content

Instantly share code, notes, and snippets.

@ishanvohra2
Last active April 22, 2024 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ishanvohra2/a22a349dea0949a4ee26925edd4cc0b6 to your computer and use it in GitHub Desktop.
Save ishanvohra2/a22a349dea0949a4ee26925edd4cc0b6 to your computer and use it in GitHub Desktop.
// Defining a cache of 5 MB size
val cacheSize = (5 * 1024 * 1024).toLong()
//Initializing instance of Cache class
val myCache = Cache(context.cacheDir, cacheSize)
//defining okhttpclient instance
val okHttpClient = OkHttpClient.Builder()
.cache(myCache)
.addInterceptor { chain ->
var request = chain.request()
request = if (hasNetwork(context))
request
.newBuilder()
.cacheControl(
CacheControl.Builder()
.maxAge(30, TimeUnit.MINUTES)
.build()
)
.build()
else
request
.newBuilder()
.cacheControl(
CacheControl.Builder()
.maxStale(1, TimeUnit.DAYS)
.build()
)
.build()
chain.proceed(request)
}
.build()
@alejandro-rios
Copy link

Please change the .txt to .kt, for better readability in the article

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment