Skip to content

Instantly share code, notes, and snippets.

@erluxman
Created May 9, 2018 15:57
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 erluxman/65d8853610d16ededc8ea56e226f7137 to your computer and use it in GitHub Desktop.
Save erluxman/65d8853610d16ededc8ea56e226f7137 to your computer and use it in GitHub Desktop.
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