Skip to content

Commit

Permalink
Fix saving of rememberSaveable values (#1531)
Browse files Browse the repository at this point in the history
* Make `Saveable` serializable

It was marked with `@Contextual`, but a serializer was never being passed in, therefore it crashes as it can't find a serializer. The class is trivial to serialize, so we can just annotate it with `@Serializable` for a serialization adapter to be generated for us.

* When deserializing a `MutableState`, also deserialize its value
  • Loading branch information
veyndan authored Sep 28, 2023
1 parent 8a90744 commit 17915ef
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package app.cash.redwood.treehouse
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import kotlin.jvm.JvmInline
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
Expand All @@ -29,13 +28,13 @@ import kotlinx.serialization.json.intOrNull

@Serializable
public class StateSnapshot(
public val content: Map<String, List<@Contextual Saveable>>,
public val content: Map<String, List<Saveable>>,
) {
public fun toValuesMap(): Map<String, List<Any?>> {
return content.mapValues { entry ->
entry.value.map {
if (it.isMutableState) {
mutableStateOf(it.value)
mutableStateOf(it.value.fromJsonElement())
} else {
it.value.fromJsonElement()
}
Expand Down Expand Up @@ -89,6 +88,7 @@ private fun JsonElement?.fromJsonElement(): Any {
}
}

@Serializable
public data class Saveable(
val isMutableState: Boolean,
val value: JsonElement,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,12 @@ class StateSnapshotTest {
val valuesMap = stateSnapshot.toValuesMap()
assertThat(valuesMap.entries.size).isEqualTo(4)
assertTrue(valuesMap["key1"]!![0] is MutableState<*>)
assertThat((valuesMap["key1"]!![0] as MutableState<*>).value).isEqualTo(JsonPrimitive(1))
assertThat((valuesMap["key1"]!![0] as MutableState<*>).value).isEqualTo(1.0)

assertThat(valuesMap["key2"]).isEqualTo(listOf(1.0))

assertThat(valuesMap["key3"]!![0] is MutableState<*>)
assertThat((valuesMap["key3"]!![0] as MutableState<*>).value).isEqualTo(JsonPrimitive("str"))
assertThat((valuesMap["key3"]!![0] as MutableState<*>).value).isEqualTo("str")

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

0 comments on commit 17915ef

Please sign in to comment.