epam / CoroutinesCache

In mobile development exists solution for caching with RxJava usage, but there is no solutions for Kotlin Coroutines. The project is to provide this functionality to mobile community.
Apache License 2.0
162 stars 7 forks source link

Parameterize cache key to support calls with different inputs #26

Closed Dartlexx closed 5 years ago

Dartlexx commented 5 years ago

Right now, CoroutineCache doesn't support caching similar data requests with different parameters.

Lets say, we are caching a search request for Products with string parameter 'productName'. Any such request would be cached under the same key, that was set in @ProviderKey("ProductsSearch"). So we may encounter following situation:

I suggest to add another lambda into getData signature, that will be written by CoroutinesCache user and that will do required modifications to @ProviderKey based on input parameters. Example:

interface CacheProviders {

    @ProviderKey("TestKey", EntryClass(Data::class))
    @LifeTime(value = 1L, unit = TimeUnit.MINUTES)
    @Expirable
    @UseIfExpired
    suspend fun getData(dataProvider: suspend () -> Data,
                                      keyModifier: (String) -> String = { s -> s }): Data
}

If such modifier is present, than base key will be modified according to provided lambda. Default implementation can be created, that takes a list of Objects to calculate overall hash of parameters.

Dartlexx commented 5 years ago

As I found out, it's extremely hard to work with KCallables in such solution, as each parametrized call is converted into generated class with contains a field with parameters. So that it makes a nightmare to call them via reflection.

So I suggest another approach now:

interface DataProvider { suspend fun getData(): Data fun parametrizeKey(baseKey: String): String = baseKey }

interface CacheProviders {

@ProviderKey("TestKey", EntryClass(Data::class))
@LifeTime(value = 1L, unit = TimeUnit.MINUTES)
@Expirable
@UseIfExpired
suspend fun getData(dataProvider: DataProvider): Data

}