MobileNativeFoundation / Store

A Kotlin Multiplatform library for building network-resilient applications
https://mobilenativefoundation.github.io/Store/
Apache License 2.0
3.16k stars 197 forks source link

Avoiding hitting network for X minutes since the last update #639

Closed matt-ramotar closed 3 months ago

matt-ramotar commented 3 months ago

From https://kotlinlang.slack.com/archives/C06007Z01HU/p1717336091375779

Hey, I couldn't find the answer but is there a way to set an expiry to the risk cache? My client doesn't update the source of truth since we only fetch from the network but I'd like to avoid going to the network for X minutes since the last update. I didn't see a way in the configuration so wanted to confirm. Right now I'm teaching it interferes internally in the source of truth and then returning nothing if expired. I need to do it for more repositories so wanted to check if there is an official way to do it. Using this setup I can stream from cache without refresh and it automatically fetches from network when the source of truth does not return anything

matt-ramotar commented 3 months ago

We have the concept of validation. If I'm understanding correctly, you can leverage Validator.

For example, if your domain model is:

data class Item(
    val id: String,
    val fetchedAt: Long
)

You can create a Validator like:

private fun isWithinRange(timestamp: Long?, duration: Duration): Boolean {
    if (timestamp == null) return false
    val now = System.currentTimeMillis()
    val durationMillis = duration.inWholeMilliseconds
    return now - timestamp <= durationMillis
}

val validator = Validator.by<Item> {
    isWithinRange(it.fetchedAt, 5.minutes)
}

And then add it to your Store:

val store = StoreBuilder.from<String, Item>(fetcher).validator(validator).build()

So if Validator returns true, we don't hit network. If Validator returns false, we hit network.