Skip to content

Instantly share code, notes, and snippets.

@k1dbl4ck
Last active June 11, 2021 06:32
Show Gist options
  • Save k1dbl4ck/895f95f3e2849840d7c9f12cd8f68889 to your computer and use it in GitHub Desktop.
Save k1dbl4ck/895f95f3e2849840d7c9f12cd8f68889 to your computer and use it in GitHub Desktop.
package com.example.android.repositories.cache
import com.example.android.repositories.cache.CachePolicy.Type.NEVER
import com.example.android.repositories.cache.CachePolicy.Type.CLEAR
import com.example.android.repositories.cache.CachePolicy.Type.ALWAYS
import com.example.android.repositories.cache.CachePolicy.Type.EXPIRES
import com.example.android.repositories.cache.CachePolicy.Type.REFRESH
abstract class CachePolicyRepository<T>(
private val localDataSource: LocalDataSource<String, CacheEntry<T>>,
private val remoteDataSource: RemoteDataSource<T>
) {
fun fetch(url: String, cachePolicy: CachePolicy): T? {
return when (cachePolicy.type) {
NEVER -> remoteDataSource.fetch(url)
ALWAYS -> {
localDataSource.get(url)?.value ?: fetchAndCache(url)
}
CLEAR -> {
localDataSource.get(url)?.value.also {
localDataSource.remove(url)
}
}
REFRESH -> fetchAndCache(url)
EXPIRES -> {
localDataSource.get(url)?.let {
if( (it.createdAt + cachePolicy.expires) > System.currentTimeMillis()) {
it.value
} else {
fetchAndCache(url)
}
} ?: fetchAndCache(url)
}
else -> null
}
}
private fun fetchAndCache(url:String): T {
return remoteDataSource.fetch(url).also {
localDataSource.set(url, CacheEntry(key = url, value = it))
}
}
}
data class CacheEntry<T>(
val key: String,
val value: T,
val createdAt: Long = System.currentTimeMillis()
)
interface LocalDataSource<in Key : Any, T> {
fun get(key: Key): T?
fun set(key: Key, value: T)
fun remove(key: Key)
fun clear()
}
interface RemoteDataSource<T> {
fun fetch(url: String): T
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment