Skip to content

Instantly share code, notes, and snippets.

@gigiperih
Created April 20, 2022 01:01
Show Gist options
  • Save gigiperih/f3bae19bb7cca7b67de0e25b20f2e4da to your computer and use it in GitHub Desktop.
Save gigiperih/f3bae19bb7cca7b67de0e25b20f2e4da to your computer and use it in GitHub Desktop.
CacheControl for OkHttpClient (to support offline mode without persistence data library)
// assuming provider is inside Hilt-Android Module
@InstallIn(SingletonComponent::class)
@Module
class NetworkModule {
...
@Provides
@Singleton
fun providesOkHttpClient(
@ApplicationContext context: Context
): OkHttpClient {
// setup cache size
val cacheSize = (5 * 1024 * 1024).toLong()
val cache = Cache(context.cacheDir, cacheSize)
// setup logging (optional)
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient.Builder()
.cache(cache)
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.addNetworkInterceptor(loggingInterceptor)
.addInterceptor { chain ->
var request = chain.request()
try {
// force fetch from network when online
request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build()
chain.proceed(request)
} catch (e: UnknownHostException) {
// retrieve from cache when network is offline
val cacheControl = CacheControl.Builder()
.onlyIfCached()
.maxStale(2, TimeUnit.HOURS)
.build()
request = request.newBuilder().cacheControl(cacheControl).build()
chain.proceed(request)
}
}
return client.build()
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment