Refactor: CollectionRepository to push changes only on local changes

This commit is contained in:
tapframe 2026-04-27 12:57:28 +05:30
parent 7ef0083a71
commit 2c81082d17
2 changed files with 11 additions and 7 deletions

View file

@ -4,7 +4,10 @@ import co.touchlab.kermit.Logger
import com.nuvio.app.features.addons.AddonRepository
import com.nuvio.app.features.addons.ManagedAddon
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.decodeFromString
@ -33,6 +36,8 @@ object CollectionRepository {
private val _collections = MutableStateFlow<List<Collection>>(emptyList())
val collections: StateFlow<List<Collection>> = _collections.asStateFlow()
private val _localChangeEvents = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
internal val localChangeEvents: SharedFlow<Unit> = _localChangeEvents.asSharedFlow()
private var rawCollectionsJson: JsonElement = JsonArray(emptyList())
private var hasLoaded = false
@ -244,16 +249,19 @@ object CollectionRepository {
internal fun applyFromRemote(collections: List<Collection>, rawJson: JsonElement) {
rawCollectionsJson = rawJson
_collections.value = collections
persist()
persist(sync = false)
}
private fun ensureLoaded() {
if (!hasLoaded) initialize()
}
private fun persist() {
private fun persist(sync: Boolean = true) {
runCatching {
CollectionStorage.savePayload(mergedCollectionsJson().toString())
if (sync) {
_localChangeEvents.tryEmit(Unit)
}
}.onFailure { e ->
log.e(e) { "Failed to persist collections" }
}

View file

@ -15,8 +15,6 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.launch
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
@ -125,9 +123,7 @@ object CollectionSyncService {
@OptIn(FlowPreview::class)
private fun observeLocalChangesAndPush() {
observeJob = scope.launch {
CollectionRepository.collections
.drop(1)
.distinctUntilChanged()
CollectionRepository.localChangeEvents
.debounce(PUSH_DEBOUNCE_MS)
.collect {
if (isSyncingFromRemote) return@collect