REST Api 호출에 캐싱처리를 하기 위해서,
OkHttp의 Cache 객체 생성시 용량을 어느정도로 만들어야할 지 고민이었고,
다음과 같은 방법으로 처리했다.(minCacheSize, maxCacheSize, ratio는 적절하게 수정할 것)
/**
* @param cacheDir 캐시 디렉토리
* @param minCacheSize 최소 캐시 용량 (예: 10MB)
* @param maxCacheSize 최대 캐시 용량 (예: 50MB)
* @param ratio 사용 가능한 용량 중 얼마를 캐시 용량으로 사용할지 결정 (예: 0.05는 5%)
*/
fun provideCache(
context: Context,
cacheDirname: String = "network_cache",
minCacheSize: Long = 10 * 1024 * 1024L, // 10MB
maxCacheSize: Long = 50 * 1024 * 1024L, // 50MB
ratio: Double = 0.05 // 사용 가능한 용량의 5% 사용
): Cache {
val cacheDir = File(context.cacheDir, cacheDirname).apply(File::mkdirs)
val statFs = StatFs(cacheDir.absolutePath)
val availableBytes = statFs.availableBytes
val calculatedSize = (availableBytes * ratio).toLong()
val cacheSize = min(max(calculatedSize, minCacheSize), maxCacheSize)
return Cache(cacheDir, cacheSize)
}