kotlinx.serialization , Encode Decode SnapshotStateList

Viewed 452

In Jetpack Compose , SnapshotStateList is a derived class from List but whenever I try to put Serializable annotation over it , it says "Serializer Not Found For This Class , To use contextual use @Contextual annotation with type or property"

I have a class ListContainer , I want to make serializable , it only contains a list of items which is a SnapshotStateList and can be smart casted to List but I don't know how to tell kotlin serializer to cast it to a List / use simple List serializer !

1 Answers
class SnapshotListSerializer<T>(private val dataSerializer:KSerializer<T>) :
    KSerializer<SnapshotStateList<T>> {

    override val descriptor: SerialDescriptor = ListSerializer(dataSerializer).descriptor

    override fun serialize(encoder: Encoder, value: SnapshotStateList<T>) {
        encoder.encodeSerializableValue(ListSerializer(dataSerializer), value as List<T>)
    }

    override fun deserialize(decoder: Decoder): SnapshotStateList<T> {
        val list = mutableStateListOf<T>()
        val items = decoder.decodeSerializableValue(ListSerializer(dataSerializer))
        list.addAll(items)
        return list
    }
}

I am not sure if it works but this is what I came up with , I'll update the answer accordingly

Related