Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rest Client for caching
package com.thorangs.retrofitcachingtest
import android.content.Context
import com.google.gson.GsonBuilder
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
/**
* Created by Laxman Bhattarai on 11/18/17.
* erluxman@gmail.com
* https://github.com/erluxman
* https://twitter.com/erluxman
*/
class RestClient private constructor(applicationContext: Context) {
private val gson = GsonBuilder()
.setLenient()
.create()!!
private var cacheSize: Long = 20 * 1024 * 1024 // 10 MB
private var cache = Cache(applicationContext.cacheDir, cacheSize)
private val httpClient = OkHttpClient.Builder()
.addInterceptor { chain ->
var request = chain.request()
if (!isOnline(applicationContext)) {
val maxStale = 60 * 60 *24
request = request?.newBuilder()
?.header("Cache-Control", "public, only-if-cached, max-stale=$maxStale")
?.build()
}
chain.proceed(request)
}
.cache(cache)
.build()
private val retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(httpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
val restAPIService: RESTApis = retrofit.create(RESTApis::class.java)
companion object {
fun instance(applicationContext: Context) = RestClient(applicationContext)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment