apolloapollo-clientapollo-androidapollo-kotlin

Apollo GraphQL Kotlin Codegen Fragment Serializable


I am using Apollo GraphQL Kotlin client and codegen. But the fragment classes generated by it cannot be saved in instance state as they are not serializable. What is the smartest way to make this happen, ideally using codegen without writing any manual code as far as possible? Thanks


Solution

  • It is generally recommended to save only simple data in the instance state (e.g. IDs), the code can then reload the data from it. If you are using the Apollo (or a third-party) cache this shouldn't go to the network and be fast.

    But if that is not practical for you, you could serialize to/from Json Strings and save that.

    // 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)
    
    

    But these strings may be lengthy and overall using IDs is probably a better solution.