Created
May 9, 2018 15:57
-
-
Save erluxman/65d8853610d16ededc8ea56e226f7137 to your computer and use it in GitHub Desktop.
Rest Client for caching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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