The following is the first few sections of a chapter from GraphQL and Android, plus headings for the remaining major sections, to give you an idea about the content of the chapter.


Fragments

As an Android developer, you probably have experience with what the Android SDK refers to as fragments. For some of you, this has been a positive experience. For the rest of you… perhaps the experience has not been as nice.

The good news is that GraphQL fragments have nothing to do with Android fragments.

The bad news is that you will have to live with yet another overloaded use of the term “fragment”.

The Role of Fragments

Oddly enough, fragments in GraphQL and Android’s fragments do have a common use case: creating a reusable bit of logic. In the case of Android’s fragments, we are trying to create a reusable bit of UI, to be applied in different ways in different places (e.g., smaller-screen vs. larger-screen layouts).

GraphQL fragments, on the other hand, reuse collections of fields. If there are 2+ places in our GraphQL document where we refer to the same collection of fields, we can define that collection once in a fragment, then reference the fragment where we ordinarily would have the fields themselves.

For example, suppose we have the following document:

query keyStuff {
  allTrips {
    id
    title
  }
}

That is nice and simple. Suppose we further expand the document, to:

query keyStuff {
  allTrips {
    id
    title
  }
}

query moreStuff {
  allTrips {
    id
    title
    priority
    duration
  }
}

We have some duplication, where both the keyStuff and moreStuff operations request the same id and title fields. But, two fields is not that much duplication… until we continue revising the document:

query keyStuff {
  allTrips {
    id
    title
    plans {
      id
      title
    }
  }
}

query moreStuff {
  allTrips {
    id
    title
    priority
    duration
    plans {
      id
      title
      priority
      duration
    }
  }
}

Now we have several axes of duplication:

All that duplication should seem like a code smell… because it is a code smell.

Fortunately, fragments can help eliminate the duplication.

Creating a Fragment

The preview of this section was traded for a bag of magic beans.

Using a Fragment

The preview of this section is unavailable right now, but if you leave your name and number at the sound of the tone, it might get back to you (BEEEEEEEEEEEEP!).

Fragments, And Your Output

The preview of this section may contain nuts.

Fragments and Your Android Code

The preview of this section is out seeking fame and fortune as the Dread Pirate Roberts.

Where Apollo-Android Generated Code Gets Generated

The preview of this section took that left turn at Albuquerque.