0
0
GraphQLquery~5 mins

Subscription syntax in GraphQL

Choose your learning style9 modes available
Introduction

Subscriptions let you get live updates from the server. They keep your app updated without asking again and again.

You want to see new chat messages as they arrive.
You want to track live scores in a sports app.
You want to update a dashboard with real-time data.
You want to get notified instantly when a new order is placed.
Syntax
GraphQL
subscription SubscriptionName {
  eventName {
    field1
    field2
  }
}

Use subscription keyword to start a subscription.

Inside, specify the event and fields you want to listen to.

Examples
This listens for new messages and gets their id, content, and sender.
GraphQL
subscription OnNewMessage {
  newMessage {
    id
    content
    sender
  }
}
This listens for score updates with team name and points.
GraphQL
subscription OnScoreUpdate {
  scoreUpdate {
    team
    points
  }
}
Sample Program

This subscription listens for new orders and fetches order ID, product name, and quantity.

GraphQL
subscription OnNewOrder {
  newOrder {
    orderId
    product
    quantity
  }
}
OutputSuccess
Important Notes

Subscriptions require a WebSocket or similar connection to keep open.

Not all GraphQL servers support subscriptions by default.

Use subscriptions only when you need real-time updates to save resources.

Summary

Subscriptions let your app get live data without asking repeatedly.

Use the subscription keyword and specify the event and fields.

They work well for chat, live scores, notifications, and dashboards.