0
0
GraphQLquery~5 mins

Why subscriptions enable real-time data in GraphQL

Choose your learning style9 modes available
Introduction

Subscriptions let your app get updates instantly when data changes. This means you see new info right away without asking again.

You want to show live chat messages as they arrive.
You need to update a dashboard with real-time stats.
You want to notify users immediately when new content is available.
You want to track live location updates on a map.
You want to reflect changes in a collaborative document instantly.
Syntax
GraphQL
subscription SubscriptionName {
  eventName {
    field1
    field2
  }
}
Subscriptions use a special GraphQL operation called 'subscription'.
They keep a connection open to send data updates automatically.
Examples
This subscription listens for new chat messages and gets their id, text, and sender immediately when added.
GraphQL
subscription NewMessages {
  messageAdded {
    id
    text
    sender
  }
}
This subscription tracks stock price changes and updates the symbol and price in real-time.
GraphQL
subscription StockPriceUpdates {
  stockPriceChanged {
    symbol
    price
  }
}
Sample Program

This subscription listens for new comments added to a post. When a comment is added, it sends the id, content, and author immediately.

GraphQL
subscription OnNewComment {
  commentAdded {
    id
    content
    author
  }
}
OutputSuccess
Important Notes

Subscriptions require a WebSocket or similar connection to keep data flowing.

They are great for live updates but can use more resources than regular queries.

Summary

Subscriptions let apps get data updates instantly without asking repeatedly.

They keep a connection open to push new data as it happens.

Use them when you want real-time updates like chats, notifications, or live stats.