Apollo GraphQL Kotlin Codegen 片段可序列化

问题描述 投票:0回答:1

我正在使用 Apollo GraphQL Kotlin 客户端和代码生成器。但它生成的片段类无法保存在实例状态中,因为它们不可序列化。实现这一目标的最明智的方法是什么,最好是使用 codegen 而不尽可能编写任何手动代码?谢谢

apollo apollo-client apollo-android apollo-kotlin
1个回答
0
投票

通常建议在实例状态中仅保存简单数据(例如ID),然后代码可以从中重新加载数据。如果您使用 Apollo(或第三方)缓存,则不应连接到网络并且速度很快。

但是如果这对您来说不切实际,您可以序列化到 Json 字符串/从 Json 字符串进行序列化并保存。

// First enable fragment impl generation in your Gradle config
apollo {
    service("service") {
        // ...
        generateFragmentImplementations.set(true)
    }
}

// Serialize your fragment to JSON
val myFragmentJsonString = MyFragmentImpl().adapter().toJsonString(myFragment)


// Deserialize the JSON to the fragment object
val myFragment = MyFragmentImpl().adapter().fromJson(Buffer().writeUtf8(myFragmentJsonString).jsonReader(), CustomScalarAdapters.Empty)

但是这些字符串可能很长,总体来说使用 ID 可能是更好的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.