Skip to content

Commit

Permalink
Serialize null in rememberSaveable
Browse files Browse the repository at this point in the history
  • Loading branch information
veyndan committed Oct 6, 2023
1 parent 5c2c4d1 commit 58c0af7
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import kotlin.jvm.JvmInline
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
Expand Down Expand Up @@ -62,13 +63,15 @@ private fun Any?.toJsonElement(): JsonElement {
is Int -> JsonPrimitive(this)
is List<*> -> JsonArray(map { it.toJsonElement() })
is JsonElement -> this
null -> JsonNull
else -> error("unexpected type: $this")
// TODO: add support to Map<*, *>
}
}

private fun JsonElement?.fromJsonElement(): Any {
private fun JsonElement.fromJsonElement(): Any? {
return when {
this is JsonNull -> null
this is JsonPrimitive -> {
if (this.isString) return content
return booleanOrNull ?: doubleOrNull ?: intOrNull ?: error("unexpected type: $this")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import assertk.assertions.containsOnly
import assertk.assertions.isEqualTo
import kotlin.test.Test
import kotlin.test.assertTrue
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonPrimitive

class StateSnapshotTest {
Expand All @@ -30,7 +31,7 @@ class StateSnapshotTest {
fun toValueMapWorksAsExpected() {
val stateSnapshot = stateSnapshot()
val valuesMap = stateSnapshot.toValuesMap()
assertThat(valuesMap.entries.size).isEqualTo(4)
assertThat(valuesMap.entries.size).isEqualTo(5)
assertTrue(valuesMap["key1"]!![0] is MutableState<*>)
assertThat((valuesMap["key1"]!![0] as MutableState<*>).value).isEqualTo(1.0)

Expand All @@ -40,6 +41,8 @@ class StateSnapshotTest {
assertThat((valuesMap["key3"]!![0] as MutableState<*>).value).isEqualTo("str")

assertThat(valuesMap["key4"]).isEqualTo(listOf("str"))

assertThat(valuesMap["key5"]).isEqualTo(listOf(null))
}

@Test
Expand All @@ -51,6 +54,7 @@ class StateSnapshotTest {
"key2" to listOf(JsonPrimitive(1)),
"key3" to listOf(JsonMutableState(JsonPrimitive("str"))),
"key4" to listOf(JsonPrimitive("str")),
"key5" to listOf(JsonNull),
)
}

Expand All @@ -60,6 +64,7 @@ class StateSnapshotTest {
"key2" to listOf(JsonPrimitive(1)),
"key3" to listOf(JsonMutableState(JsonPrimitive("str"))),
"key4" to listOf(JsonPrimitive("str")),
"key5" to listOf(JsonNull),
),
)

Expand All @@ -68,5 +73,6 @@ class StateSnapshotTest {
"key2" to listOf(1),
"key3" to listOf(mutableStateOf("str")),
"key4" to listOf("str"),
"key5" to listOf(null),
)
}

0 comments on commit 58c0af7

Please sign in to comment.