Skip to content

Instantly share code, notes, and snippets.

@ishanvohra2
Created April 10, 2024 09:08
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/53d1e27fb19c5d52095291f50d0a9949 to your computer and use it in GitHub Desktop.
Save ishanvohra2/53d1e27fb19c5d52095291f50d0a9949 to your computer and use it in GitHub Desktop.
class RetrofitClient(private val context: Context) {
val cacheSize = (5 * 1024 * 1024).toLong()
val instance: Api by lazy {
val myCache = Cache(context.cacheDir, cacheSize)
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)
}
.addInterceptor(HttpLoggingInterceptor().apply {
this.level = HttpLoggingInterceptor.Level.BODY }
)
.build()
val retrofit = Retrofit.Builder()
.baseUrl("BASE_URL")
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
retrofit.create(Api::class.java)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment