Created
January 4, 2021 23:42
-
-
Save yhirano/3cad99716ef7212f3f13ef6c313993ec to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import android.os.SystemClock | |
| /** | |
| * @param expireTime Cache expire time(ms). | |
| */ | |
| class ExpiringCache<V: Any>(private val expireTime: Long) { | |
| private var cache: V? = null | |
| private var expirationTime: Long = 0 | |
| fun get(): V? { | |
| synchronized(this) { | |
| val value = cache | |
| if (value != null && elapsedRealtime() >= expirationTime) { | |
| remove() | |
| return null | |
| } else { | |
| return value | |
| } | |
| } | |
| } | |
| fun set(value: V): V? { | |
| synchronized(this) { | |
| val previousValue = cache | |
| cache = value | |
| expirationTime = elapsedRealtime() + expireTime | |
| return previousValue | |
| } | |
| } | |
| fun elapsedRealtime(): Long { | |
| return SystemClock.elapsedRealtime() | |
| } | |
| fun getExpiryTime(): Long { | |
| return expirationTime | |
| } | |
| fun removeExpiryTime() { | |
| expirationTime = 0 | |
| } | |
| fun remove(): V? { | |
| synchronized(this) { | |
| val previousValue = cache | |
| cache = null | |
| expirationTime = 0 | |
| return previousValue | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment