2

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 !

Waqas Tahir
  • 7,171
  • 5
  • 25
  • 47
  • 1
    As `SnapshotStateList` is not serializable, I believe you need to create a custom serializer for it and use it as described here: https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#serializing-3rd-party-classes . And even if `SnapshotStateList` implements a list, it can only help with serializing, but not with deserializing. – broot Jun 27 '21 at 18:53
  • >but I don't know how to tell kotlin serializer to cast it As usual, with [unsafe cast operator](https://kotlinlang.org/docs/typecasts.html#unsafe-cast-operator) `private inline fun encode(snapshotStateList: SnapshotStateList) = Json.encodeToString(snapshotStateList as List)` – Михаил Нафталь Jun 28 '21 at 18:09
  • its inside another class which has serializable annotation over it ! – Waqas Tahir Jun 29 '21 at 07:22

1 Answers1

2
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

Waqas Tahir
  • 7,171
  • 5
  • 25
  • 47