gpt4 book ai didi

Kotlin 序列化 : How to serialize MutableStateFlow?

转载 作者:行者123 更新时间:2023-12-04 07:29:40 27 4
gpt4 key购买 nike

我有以下代码

@Serializeable
class Car {
val speed = MutableStateFlow<Int>(0)
var isMoving: Boolean = false
}

问题是如何序列化MutableStateFlow?

最佳答案

您需要为 MutableStateFlow<Int> 创建专门的序列化程序.

要么基于@Tenfour04 建议的通用序列化器

object MutableStateFlowOfIntsSerializer :
KSerializer<MutableStateFlow<Int>> by MutableStateFlowSerializer(Int.serializer())

class MutableStateFlowSerializer<T>(private val dataSerializer: KSerializer<T>) : KSerializer<MutableStateFlow<T>> {
override val descriptor: SerialDescriptor = dataSerializer.descriptor
override fun serialize(encoder: Encoder, value: MutableStateFlow<T>) = dataSerializer.serialize(encoder, value.value)
override fun deserialize(decoder: Decoder) = MutableStateFlow(dataSerializer.deserialize(decoder))
}

或从头开始:

object MutableStateFlowOfIntsSerializer : KSerializer<MutableStateFlow<Int>> {
override val descriptor: SerialDescriptor = Int.serializer().descriptor
override fun serialize(encoder: Encoder, value: MutableStateFlow<Int>) =
Int.serializer().serialize(encoder, value.value)

override fun deserialize(decoder: Decoder) = MutableStateFlow(Int.serializer().deserialize(decoder))
}

并将其连接到 speed领域:

@Serializable
class Car {
@Serializable(with = MutableStateFlowOfIntsSerializer::class)
val speed = MutableStateFlow(0)
var isMoving: Boolean = false
}

请注意,此序列化方法将序列化 speed字段不管 encodeDefaults = false设置

关于Kotlin 序列化 : How to serialize MutableStateFlow<Float>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68019188/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com