From 540d5cce7c042b104081c43a45eb1477a9dd1bb9 Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Wed, 29 Jun 2022 19:43:58 +0600 Subject: [PATCH] start add full repos caches --- repos/cache/build.gradle | 2 +- .../repos/cache/full/FullCRUDCacheRepo.kt | 41 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 repos/cache/src/commonMain/kotlin/dev/inmo/micro_utils/repos/cache/full/FullCRUDCacheRepo.kt diff --git a/repos/cache/build.gradle b/repos/cache/build.gradle index e128b1e3cff..1ca610cbfdf 100644 --- a/repos/cache/build.gradle +++ b/repos/cache/build.gradle @@ -15,4 +15,4 @@ kotlin { } } } -} \ No newline at end of file +} diff --git a/repos/cache/src/commonMain/kotlin/dev/inmo/micro_utils/repos/cache/full/FullCRUDCacheRepo.kt b/repos/cache/src/commonMain/kotlin/dev/inmo/micro_utils/repos/cache/full/FullCRUDCacheRepo.kt new file mode 100644 index 00000000000..0fa797917bc --- /dev/null +++ b/repos/cache/src/commonMain/kotlin/dev/inmo/micro_utils/repos/cache/full/FullCRUDCacheRepo.kt @@ -0,0 +1,41 @@ +package dev.inmo.micro_utils.repos.cache.full + +import dev.inmo.micro_utils.pagination.Pagination +import dev.inmo.micro_utils.pagination.PaginationResult +import dev.inmo.micro_utils.repos.* +import dev.inmo.micro_utils.repos.cache.ReadCRUDCacheRepo +import dev.inmo.micro_utils.repos.cache.cache.KVCache +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.onEach + + +open class FullReadCRUDCacheRepo( + parentRepo: ReadCRUDRepo, + kvCache: KVCache, + idGetter: (ObjectType) -> IdType +) : ReadCRUDRepo, ReadCRUDCacheRepo(parentRepo, kvCache, idGetter) { + override suspend fun getByPagination(pagination: Pagination): PaginationResult { + return kvCache.values(pagination) + } + + override suspend fun count(): Long = kvCache.count() +} + +open class FullCRUDCacheRepo( + parentRepo: CRUDRepo, + kvCache: KVCache, + scope: CoroutineScope = CoroutineScope(Dispatchers.Default), + idGetter: (ObjectType) -> IdType +) : FullReadCRUDCacheRepo( + parentRepo, + kvCache, + idGetter +), + CRUDRepo, + WriteCRUDRepo by parentRepo { + protected val onNewJob = parentRepo.newObjectsFlow.onEach { kvCache.set(idGetter(it), it) }.launchIn(scope) + protected val onUpdatedJob = parentRepo.updatedObjectsFlow.onEach { kvCache.set(idGetter(it), it) }.launchIn(scope) + protected val onRemoveJob = parentRepo.deletedObjectsIdsFlow.onEach { kvCache.unset(it) }.launchIn(scope) +}