Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.launch
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
Expand Down Expand Up @@ -65,6 +66,16 @@ object CollectionSyncService {
val remoteJson = remoteCollectionsJson.toString()
val localJson = CollectionRepository.exportToJson()

if (isRemoteCollectionsEmpty(remoteCollectionsJson)) {
val currentCollections = CollectionRepository.collections.value
if (currentCollections.isNotEmpty()) {
log.i {
"pullFromServer — remote empty, preserving local ${currentCollections.size} collections"
}
return
}
}

if (remoteJson == localJson) {
log.d { "pullFromServer — remote matches local, no update needed" }
return
Expand Down Expand Up @@ -132,3 +143,13 @@ object CollectionSyncService {
}
}
}

internal fun isRemoteCollectionsEmpty(remoteCollectionsJson: JsonElement): Boolean =
when (remoteCollectionsJson) {
is JsonArray -> remoteCollectionsJson.isEmpty()
is JsonNull -> true
else -> {
val serialized = remoteCollectionsJson.toString()
serialized == "[]" || serialized == "null"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.nuvio.app.features.collection

import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonPrimitive
import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class CollectionSyncServiceTest {
@Test
fun emptyRemoteJsonArrayIsTreatedAsEmpty() {
assertTrue(isRemoteCollectionsEmpty(JsonArray(emptyList())))
}

@Test
fun nullRemoteJsonIsTreatedAsEmpty() {
assertTrue(isRemoteCollectionsEmpty(JsonNull))
}

@Test
fun nonEmptyRemoteJsonArrayIsNotEmpty() {
assertFalse(isRemoteCollectionsEmpty(JsonArray(listOf(JsonPrimitive("collection-id")))))
}
}