Fragments
Apollo Android supports GraphQL fragments. Fragments allow you to define a set of fields that can be reusable in your queries.
GraphQL
Launch.graphql
1fragment launchFragment on Launch {
2 id
3 site
4 mission {
5 name
6 }
7}
8
9query LaunchDetails($id:ID!) {
10 launch(id: $id) {
11 ...launchFragment
12 }
13}
Apollo Android will generate a LaunchFragment
class that can be reused in different queries:
Kotlin
LaunchFragment.kt
1data class LaunchFragment(
2 val __typename: String = "Launch",
3 val id: String,
4 val site: String?,
5 val mission: Mission?
6 )
Your generated models will have a .fragments
property to access the fragments:
Kotlin
1println("Mission site: ${launch.fragments.launchFragment.site}")
To reuse a fragment, use it in any other query:
GraphQL
Launch.graphql
1// ...
2
3query LaunchList {
4 launches {
5 launches {
6 ...launchFragment
7 }
8 }
9}
You can define your fragment in any .graphql
file. The compiler merges all .graphql
files so it doesn't matter if you have multiple files or put everything in the same file.