Overview
Subscriptions are operations that subscribe us to real-time data. And when we combine this with a federated architecture—propagating real-time events across our graph—the results are even more powerful.
Review: Subscriptions in GraphQL
In contrast to queries, subscribing to some piece of data involves a different kind of connection to the server. The server uses this connection to notify clients immediately as new events occur. Queries, by contrast, place the burden on the client to check in every time it wants an update.
Queries are a great solution when data doesn't change all that often, or when a page refresh suffices for retrieving the latest data. For the real-time, mission critical updates, we'll reach for the Subscription
type.
The Subscription
type
Just like Query
and Mutation
, Subscription
is a root-level operation type we can add to our schema. It's defined with the type
keyword, followed by Subscription
with a capital 'S'.
type Subscription {}
The fields we give to our Subscription
type are "entrypoints" to our schema, just like the fields on our Query
and Mutation
types. We define them the same way too: with a descriptive name (typically describing the kind of event we're subscribing to), any arguments they might accept, and the type that they return.
type Subscription {listenForMessageInConversation(id: ID!): Message}
A subscription field like listenForMessageInConversation
might give the client a way to be notified anytime a new message is posted. And as the return type for each subscription event, we'd receive the new Message
and could query any of its fields to learn more about it.
Share your questions and comments about this lesson
Your feedback helps us improve! If you're stuck or confused, let us know and we'll help you out. All comments are public and must follow the Apollo Code of Conduct. Note that comments that have been resolved or addressed may be removed.
You'll need a GitHub account to post below. Don't have one? Post in our Odyssey forum instead.