I have a Retrofit Kotlin singleton where I need a context to access the cacheDir, what would be the best current approach to solve this?:
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.Cache
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
import java.io.File
import java.util.concurrent.TimeUnit
private const val BASE_URL = "https://5c5c8ba5345018a0014aa1b24.mockapi.io/api/test"
/**
* Build the Moshi object that Retrofit will be using, making sure to add the Kotlin adapter for
* full Kotlin compatibility.
*/
private val moshi: Moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
// Create a cache object
const val cacheSize = 1 * 1024 * 1024 // 1 MB
val httpCacheDirectory = File(cacheDir, "http-cache")
val cache = Cache(httpCacheDirectory, cacheSize.toLong())
// create a network cache interceptor, setting the max age to 1 minute
private val networkCacheInterceptor = Interceptor { chain ->
val response = chain.proceed(chain.request())
val cacheControl = CacheControl.Builder()
.maxAge(1, TimeUnit.MINUTES)
.build()
response.newBuilder()
.header("Cache-Control", cacheControl.toString())
.build()
}
// Create the logging interceptor
private val loggingInterceptor = HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY)
// Create the httpClient, configure it
// with cache, network cache interceptor and logging interceptor
// TODO: don't use loggingInterceptor in release build.
private val httpClient = OkHttpClient.Builder()
.cache(cache)
.addNetworkInterceptor(networkCacheInterceptor)
.addInterceptor(loggingInterceptor)
.build()
// Create the Retrofit with the httpClient
private val retrofit = Retrofit.Builder()
.baseUrl("http://localhost/")
.addConverterFactory(MoshiConverterFactory.create(moshi))
.client(httpClient)
.build()
/**
* A public interface that exposes the [getWeatherForecasts] method
*/
interface WeatherForecastsApiService {
@GET(BASE_URL)
suspend fun getWeatherForecasts(): List<WeatherForecastEntity>
}
/**
* A public Api object that exposes the lazy-initialized Retrofit service.
*/
object WeatherForecastApi {
val RETROFIT_SERVICE : WeatherForecastsApiService by lazy {
retrofit.create(WeatherForecastsApiService::class.java)
}
}