0
0
GraphQLquery~5 mins

Subscription filtering in GraphQL

Choose your learning style9 modes available
Introduction

Subscription filtering helps you get only the updates you care about in real time. It saves data and keeps your app fast.

You want to see live updates about your favorite sports team only.
You want to get notified when a specific product's price changes.
You want to follow messages in a chat room you joined, not all chat rooms.
You want to track changes in your own user profile but not others'.
Syntax
GraphQL
subscription SubscriptionName($filter: FilterType) {
  eventName(filter: $filter) {
    field1
    field2
  }
}
Use variables to pass filter conditions to the subscription.
Filters limit which events trigger updates to your client.
Examples
This subscription listens only for new messages in a specific chat room.
GraphQL
subscription OnNewMessage($roomId: ID!) {
  messageAdded(filter: {roomId: $roomId}) {
    id
    content
    sender
  }
}
This subscription sends updates only when the price of a certain product changes.
GraphQL
subscription OnPriceChange($productId: ID!) {
  priceUpdated(filter: {productId: $productId}) {
    productId
    newPrice
  }
}
Sample Program

This subscription listens for status changes of a specific user only.

GraphQL
subscription OnUserStatusChange($userId: ID!) {
  userStatusChanged(filter: {userId: $userId}) {
    userId
    status
  }
}
OutputSuccess
Important Notes

Filters help reduce unnecessary data and improve app performance.

Make sure your backend supports filtering in subscriptions.

Summary

Subscription filtering sends only relevant real-time updates.

Use filters to specify which events you want to receive.

This keeps your app efficient and user-friendly.