WriteStandardKeyValueRepo#unsetWithValues

This commit is contained in:
2020-12-05 17:52:37 +06:00
parent 3ae9b3e576
commit 091cb38339
9 changed files with 74 additions and 7 deletions

View File

@@ -1,7 +1,6 @@
package dev.inmo.micro_utils.repos
import dev.inmo.micro_utils.pagination.Pagination
import dev.inmo.micro_utils.pagination.PaginationResult
import dev.inmo.micro_utils.pagination.*
import kotlinx.coroutines.flow.Flow
interface ReadStandardKeyValueRepo<Key, Value> : Repo {
@@ -20,6 +19,7 @@ interface WriteStandardKeyValueRepo<Key, Value> : Repo {
suspend fun set(toSet: Map<Key, Value>)
suspend fun unset(toUnset: List<Key>)
suspend fun unsetWithValues(toUnset: List<Value>)
}
typealias WriteKeyValueRepo<Key,Value> = WriteStandardKeyValueRepo<Key, Value>
@@ -35,5 +35,13 @@ suspend inline fun <Key, Value> WriteStandardKeyValueRepo<Key, Value>.unset(
vararg k: Key
) = unset(k.toList())
interface StandardKeyValueRepo<Key, Value> : ReadStandardKeyValueRepo<Key, Value>, WriteStandardKeyValueRepo<Key, Value>
interface StandardKeyValueRepo<Key, Value> : ReadStandardKeyValueRepo<Key, Value>, WriteStandardKeyValueRepo<Key, Value> {
override suspend fun unsetWithValues(toUnset: List<Value>) = toUnset.forEach { v ->
doWithPagination {
keys(v, it).also {
unset(it.results)
}
}
}
}
typealias KeyValueRepo<Key,Value> = StandardKeyValueRepo<Key, Value>

View File

@@ -105,6 +105,10 @@ open class MapperWriteStandardKeyValueRepo<FromKey, FromValue, ToKey, ToValue>(
k.toOutKey()
}
)
override suspend fun unsetWithValues(toUnset: List<FromValue>) = to.unsetWithValues(
toUnset.map { it.toOutValue() }
)
}
@Suppress("NOTHING_TO_INLINE")

View File

@@ -35,10 +35,10 @@ class KeyValueStore<T : Any> internal constructor (
}
private val onNewValueChannel = MutableSharedFlow<Pair<String, T>>()
private val onValueRemovedChannel = MutableSharedFlow<String>()
private val _onValueRemovedFlow = MutableSharedFlow<String>()
override val onNewValue: Flow<Pair<String, T>> = onNewValueChannel.asSharedFlow()
override val onValueRemoved: Flow<String> = onValueRemovedChannel.asSharedFlow()
override val onValueRemoved: Flow<String> = _onValueRemovedFlow.asSharedFlow()
init {
cachedData ?.let {
@@ -136,6 +136,18 @@ class KeyValueStore<T : Any> internal constructor (
sharedPreferences.edit {
toUnset.forEach { remove(it) }
}
toUnset.forEach { onValueRemovedChannel.emit(it) }
toUnset.forEach { _onValueRemovedFlow.emit(it) }
}
override suspend fun unsetWithValues(toUnset: List<T>) {
val keysToRemove = sharedPreferences.all.mapNotNull { if (it.value in toUnset) it.key else null }
sharedPreferences.edit {
keysToRemove.map {
remove(it)
}
}
keysToRemove.forEach {
_onValueRemovedFlow.emit(it)
}
}
}