-
-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
5 changed files
with
117 additions
and
17 deletions.
There are no files selected for viewing
39 changes: 39 additions & 0 deletions
39
model/src/commonMain/kotlin/dev/datlag/burningseries/model/Cacheable.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
package dev.datlag.burningseries.model | ||
|
||
import kotlinx.datetime.Clock | ||
import kotlinx.datetime.Instant | ||
import kotlin.time.Duration | ||
import kotlin.time.Duration.Companion.hours | ||
|
||
class Cacheable<T>(private val timeAlive: Duration = 2.hours) { | ||
private var cachedOn: Instant? = null | ||
private var data: T? = null | ||
|
||
fun cache(data: T): T { | ||
this.data = data | ||
this.cachedOn = Clock.System.now() | ||
return data | ||
} | ||
|
||
fun getAlive(): T? { | ||
val cacheTime = cachedOn ?: return null | ||
|
||
return if (cacheTime.epochSeconds < Clock.System.now().minus(timeAlive).epochSeconds) { | ||
null | ||
} else { | ||
data | ||
} | ||
} | ||
|
||
fun getUnAlive(): T? { | ||
return data | ||
} | ||
|
||
operator fun get(unAlive: Boolean = false): T? { | ||
return if (unAlive) { | ||
getUnAlive() | ||
} else { | ||
getAlive() | ||
} | ||
} | ||
} |
This file contains 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
This file contains 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
This file contains 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
This file contains 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