0
0
GraphQLquery~5 mins

Subscription lifecycle in GraphQL

Choose your learning style9 modes available
Introduction

Subscriptions let you get live updates from the database. They keep you informed when data changes without asking again and again.

You want to see new messages in a chat app as soon as they arrive.
You need to update a dashboard when sales numbers change.
You want to show live scores in a sports app.
You want to track real-time location updates on a map.
You want to notify users instantly when their order status changes.
Syntax
GraphQL
subscription SubscriptionName {
  eventName {
    field1
    field2
  }
}
Use the keyword subscription instead of query to start a subscription.
Inside the subscription, specify the event or data you want to listen to and the fields you want to receive.
Examples
This subscription listens for new messages and returns their id, content, and sender.
GraphQL
subscription OnNewMessage {
  newMessage {
    id
    content
    sender
  }
}
This subscription listens for updates to orders and returns the order ID and new status.
GraphQL
subscription OnOrderUpdate {
  orderUpdated {
    orderId
    status
  }
}
Sample Program

This subscription listens for new users added to the database and returns their id, name, and email.

GraphQL
subscription OnNewUser {
  userAdded {
    id
    name
    email
  }
}
OutputSuccess
Important Notes

Subscriptions keep the connection open to send updates as they happen.

They are great for real-time apps but can use more resources than simple queries.

Make sure your server supports subscriptions and you handle connection errors gracefully.

Summary

Subscriptions let you get live updates automatically.

Use the subscription keyword and specify the event and fields.

They are perfect for chat apps, live dashboards, and notifications.