Skip to content

Instantly share code, notes, and snippets.

@florian-do
Created May 2, 2019 01:50
Show Gist options
  • Save florian-do/d78a694462f65acf6c66e53b28793144 to your computer and use it in GitHub Desktop.
Save florian-do/d78a694462f65acf6c66e53b28793144 to your computer and use it in GitHub Desktop.
RefreshStrategy
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
import java.util.*
class RefreshStrategy(c: Context) {
private val map: MutableMap<Class<*>, Long> = hashMapOf()
private val forceRefresh: MutableMap<Class<*>, Boolean> = hashMapOf()
private val sp : SharedPreferences = PreferenceManager.getDefaultSharedPreferences(c)
companion object {
private const val TAG = "RefreshStrategy"
}
init {
// set here the refresh time in sec
map[Playlist::class.java] = 60
forceRefresh[Playlist::class.java] = false
}
fun shouldRefresh(className : Class<*>) : Boolean {
val time = sp.getLong(className.simpleName, 0)
val expire = Date(time + (map[className]!! * 60000))
val now = Date()
return expire.before(now)
}
fun forceRefresh(className : Class<*>) {
forceRefresh[className] = true
}
fun shouldForceRefresh(className : Class<*>) : Boolean = forceRefresh[className]!!
fun refresh(className : Class<*>) {
sp.edit()
.putLong(className.simpleName, Date().time)
.apply()
forceRefresh[className] = false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment