https://kotlinlang.org logo
Title
n

nitrog42

05/04/2022, 12:51 PM
What is the preferred way to use Saver with “complex” object ?
data class Container(val name: String, val items: List<Item>)
data class Item(val id: Int)
I know how to create a Saver for each (an object, or a list), but I’m not sure how to handle object that contains a list
I shall precise that the list contains few items and I’m looking for using rememberSaveable/SavedStateHandle, I already have a database but that’s not the usecase
right now my first working sample :
val ContainerSaver = listSaver<Container?, Any?>(
    save = {
        if(it != null) {
            listOf(it.name) + it.items.map {
                it.id
            }
        } else {
            emptyList()
        }
    },
    restore = {
        if(it.isNotEmpty()) {
            Container(it[0] as String,
                it.drop(1).map {
                    Item(it as Int)
                }
            )
        } else {
            null
        }
    }
)
not beautiful but working ! I’m not sure how it’s working behind the scene as
save = {
    listOf(
"name",
listOf(1,2,3)
}
is working in the restore, so that’s impressive!